I'm defining a Python class:
class Foo:
bar = property(lambda self: Bar(self))
I want to annotate the bar
property to say that it contains an item of class Bar
. Is there an accepted way of doing that? I know that this is valid Python syntax:
bar: Bar = property(lambda self: Bar(self))
But is this an accepted way of annotating a property?
To annotate return value type, add -> immediately after closing the parameter parentheses, just before the function definition colon( : ): def announcement(language: str, version: float) -> str: ... The function now has type hints showing that it receives str and float arguments, and returns str .
Type hints work best in modern Pythons. Annotations were introduced in Python 3.0, and it's possible to use type comments in Python 2.7. Still, improvements like variable annotations and postponed evaluation of type hints mean that you'll have a better experience doing type checks using Python 3.6 or even Python 3.7.
Annotations were introduced in Python 3.0 originally without any specific purpose. They were simply a way to associate arbitrary expressions to function arguments and return values. Years later, PEP 484 defined how to add type hints to your Python code, based off work that Jukka Lehtosalo had done on his Ph.
So in short: no, they will not cause any run-time effects, unless you explicitly make use of them.
If you want to be safe, simply refactor it into using the decorator form and specify a return value:
class Foo:
@property
def bar(self) -> Bar:
return Bar(self)
this is also the form used in typeshed
which collects stubs annotating the standard library and also smoothly passes through mypy
.
As for variable annotation syntax of Python 3.6, the form:
bar: Bar = property(lambda self: Bar(self))
is currently acceptable when checking with mypy
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With