Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the -> (dash-greater-than arrow symbol) mean in a Python method signature? [duplicate]

There is a ->, or dash-greater-than symbol at the end of a python method, and I'm not sure what it means. One might call it an arrow as well.

Here is the example:

@property def get_foo(self) -> Foo:     return self._foo 

where self._foo is an instance of Foo.

My guess is that it is some kind of static type declaration, to tell the interpreter that self._foo is of type Foo. But when I tested this, if self._foo is not an instance of Foo, nothing unusual happens. Also, if self._foo is of a type other than Foo, let's say it was an int, then type(SomeClass.get_foo()) returns int. So, what's the point of -> Foo?

This concept is hard to lookup because it is a symbol without a common name, and the term "arrow" is misleading.

like image 507
modulitos Avatar asked Jul 16 '15 05:07

modulitos


People also ask

What is -> symbol in Python used for?

This is function annotations. It can be use to attach additional information to the arguments or a return values of functions. It is a useful way to say how a function must be used.

What does -> None do in Python?

The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string.

What is in Python function?

In Python, a function is a group of related statements that performs a specific task. Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable. Furthermore, it avoids repetition and makes the code reusable.


1 Answers

This is function annotations. It can be use to attach additional information to the arguments or a return values of functions. It is a useful way to say how a function must be used. Functions annotations are stored in a function's __annotations__ attribute.

Use Cases (From documentation)

  • Providing typing information

    • Type checking
    • Let IDEs show what types a function expects and returns
    • Function overloading / generic functions
    • Foreign-language bridges
    • Adaptation
    • Predicate logic functions
    • Database query mapping
    • RPC parameter marshaling
  • Other information

    • Documentation for parameters and return values

From python-3.5 it can be used for Type Hints

like image 121
styvane Avatar answered Oct 04 '22 13:10

styvane