[Tutor] enforcing specific types in Python 3.5?
Peter Otten
__peter__ at web.de
Fri Oct 14 03:48:37 EDT 2016
James Hartley wrote:
> I have implemented the equivalent of "insert if unique" in Python &
> SQLAlchemy to help with data normalization. However to help minimize the
> number of preliminary SELECT statements needed, it helps to check types
> through calls to isinstance() before getting to the salient code.
> Unfortunately, the code begins to be cluttered with type-checking
> minutiae.
>
> While researching this problem, I have found potential solutions like the
> following:
>
> http://stackoverflow.com/questions/9305751/force-python-class-member-variable-to-be-specific-type
>
> ...but given that Python 3.5 has syntactically understands gradual typing,
> I have wondered whether addition of this feature offers anything over use
> of property() as described above. Toy examples have not revealed anything
> useful on this front:
>
> $ cat example.py
> #!/usr/bin/env python
>
> class Foobar():
> def __init__(self, value):
> self.value = value
>
> def f(s: str) -> int:
> print(s)
> return 3.14
>
> def main():
> i = f('foobar')
> print(type(i))
> print('i = "{}"'.format(i))
> i = f(Foobar(3))
> print(type(i))
> print('i = "{}"'.format(i))
>
> if __name__ == '__main__':
> main()
> $ python example.py
> foobar
> <class 'float'>
> i = "3.14"
> <__main__.Foobar object at 0x85b8aaac>
> <class 'float'>
> i = "3.14"
> $
>
> I understand that gradual typing may be useful with static analysis, but I
> don't see that any type enforcement occurs by default at runtime. Am I
> missing something here? Is there a better solution for type enforcement?
Quoting <https://www.python.org/dev/peps/pep-0484>:
"""
no type checking happens at runtime . Instead, the proposal assumes the
existence of a separate off-line type checker which users can run over their
source code voluntarily. Essentially, such a type checker acts as a very
powerful linter
"""
You need an external tool
http://mypy-lang.org/
to perform a type check:
(mypylang)$ mypy example.py
example.py: note: In function "f":
example.py:9: error: Incompatible return value type (got "float", expected
"int")
(mypylang)$
More information about the Tutor
mailing list