Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the same type as class in method's parameter following PEP484? [duplicate]

My question is related with the new Python's type hints. I'm trying to add a type hint in an object's method who has a parameter of the same type of the object, but PyCharm are marking me as error (unresolved reference 'Foo'). The problem is as follows:

class Foo:

    def foo_method(self, other_foo: Foo):
        return "Hello World!"

So the question is how to define the type of other_foo parameter properly. Maybe __class__ is correct?

like image 446
garciparedes Avatar asked Jun 28 '17 09:06

garciparedes


People also ask

What is PEP 484?

PEP 484, which provides a specification about what a type system should look like in Python3, introduced the concept of type hints.

What is the use of type () function in Python?

Syntax of the Python type() function The type() function is used to get the type of an object. When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object.

How do you create a type in Python?

First, extract the class body as string. Second, create a class dictionary for the class namespace. Third, execute the class body to fill up the class dictionary. Finally, create a new instance of type using the above type() constructor.


1 Answers

Inside of the class, the class is not defined yet, causing a NameError (and PyCharm to complain).

To get around this, use forward declarations:

class Foo:
    def foo_method(self, other_foo: "Foo"):
        return "Hello World!"

Basically, if a type annotations is a string, it is evaled after the whole module is loaded, so it can evaluate to the Foo class.

like image 196
Artyer Avatar answered Sep 19 '22 15:09

Artyer