4 ms·
> Type hints in Python are mostly for linters and code checkers, as they are not enforced at run time by CPython. PEP 585 When you think about why that is, it
by wodenokoto 6y ago
> Type hints in Python are mostly for linters and code checkers, as they are not enforced at run time by CPython. PEP 585
When you think about why that is, it makes sense, but I still find it annoying that while my type hints are not enforced, if I type-hint to an object that doesn't exist, I still get a run-time error.
I kinda wish that these hints would just be interpreted as comments during runtime.
- techdragon 6y agoThere’s a good pattern for this using “if typing.TYPE_CHECKING:”... by either only importing them while type checking or by checking “if not typing.TYPE_CHECKING:” you could set an object type like Any, or your own custom one, as the value of all your imported types which should avoid most runtime errors I can think of.
- leontrolski 6y agoThis doesn't solve your problem, but for anyone else reading who may not be aware - there is (at least one) library that does runtime checking with your type hints: https://typeguard.readthedocs.io/en/latest/userguide.html#using-the-pytest-plugin https://typeguard.readthedocs.io/en/latest/userguide.html#us...
- BerislavLopac 6y agoI'm not sure what do you mean by "type-hint to an object that doesn't exist"? The objects are not type-hinted; variables are. A variable in Python will always have a value (because it's just a label on a value, not a container), and that value will always be an object, and objects in Python always have a type. If you mean that you are passing a variable that can have a value of None, this is what Optional[<type>] is for... Or maybe I'm missing something -- can you give an example?
- wodenokoto 6y agoimport numpy as np def f(x:numpy.array): pass Since numpy doesn’t exist in my namespace I get a runtime error (NameError) for a part of my code that supposedly isn’t used. I just feel like this should throw errors when running mypy and not when running my script.
- kjagiello 6y agohttps://www.python.org/dev/peps/pep-0563/ https://www.python.org/dev/peps/pep-0563/
- BerislavLopac 6y agoThis is exactly what happens starting with Python 3.7, which implements PEP 563 [0]; you just need to enable it by importing annotations from __future__. Starting from Python 3.10 that will be the default. [0] [0] https://docs.python.org/3/whatsnew/3.7.html#pep-563-postponed-evaluation-of-annotations https://docs.python.org/3/whatsnew/3.7.html#pep-563-postpone...
- fdomingues 6y agoSince Python 3.7 you can postpone evaluation of the annotations[1]. You can do something like this: from __future__ import annotations Class Node: parent: Optional[Node] [1] https://www.python.org/dev/peps/pep-0563/ https://www.python.org/dev/peps/pep-0563/