With Python 3.5, we have not only PEP 483 , PEP 484 , but also a typing module that implements it.
For a complete understanding, you can read these 3 documents. But for your specific case, the short answer is that in the PEP484 area you can work with your own types in 4 ways:
If you are looking for the most:
additional information visible to my own type checking tool, but invisible to any PEP-484 type checking tool
then the second approach gives you exactly that. If you do:
Int32 = int Int64 = int x = 0 # type: Int32 y = 0 # type: Int64
Then Int32 and Int64 will be the same in the PEP484 area, but you can add some additional checks by looking at the AST (abstract syntax tree) of your code using the community typed-ast supported typed-ast . This module parses type comments in addition to code, so you can read the exact use of the annotation and thus get additional type information for x and y .
And, if invisibility is not number one priority, then:
instead of class Int32(int): pass I would rather do typing.NewType('Int32', int) and
instead of combine(Int32, Metre) I would use typing.Union[Int32, Metre] .
i.e.
Int32 = typing.NewType('Int32', int) class Metre: pass x = [Int32(1)] # type: List[Int32] y = Int32(1) # type: typing.Union[Int32, Metre] print(x[0] + 1) # ok, since Int32 is still int y = Metre() # ok, since y can be Int32 or Metre
In the above code, you can run the community-supported static type-checker mypy .
Both typed-ast and mypy are now (2016) under a very active development. Not everything works as expected, but as far as I can see, they are good enough for many use cases, and there are no alternatives.
mbdevpl
source share