Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python type annotations: Any way to annotate a property?

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?

like image 642
Ram Rachum Avatar asked Feb 26 '17 00:02

Ram Rachum


People also ask

How do you annotate type in Python?

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 .

Should you use type annotations Python?

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.

What is __ annotations __ in Python?

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.

Do type annotations make Python faster?

So in short: no, they will not cause any run-time effects, unless you explicitly make use of them.


1 Answers

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.

like image 196
Dimitris Fasarakis Hilliard Avatar answered Nov 09 '22 15:11

Dimitris Fasarakis Hilliard