Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type is undefined inside a class definition #2182

Closed
songyang-dev opened this issue Dec 17, 2021 · 2 comments
Closed

Type is undefined inside a class definition #2182

songyang-dev opened this issue Dec 17, 2021 · 2 comments

Comments

@songyang-dev
Copy link

The type of a variable is not defined inside a method of its own class?
image

@erictraut
Copy link
Contributor

This is correct. If you try to run this in the Python interpreter, it will generate a runtime exception because the UMLClass isn't defined at that point of execution. You can work around this by enclosing the type annotation in quotes. Type checkers will then treat it as a "forward-declared reference". This is the recommended approach documented in PEP 484.

@linux4life798
Copy link

Update:

  • If you are using Python 3.7+, you can use the future statement from __future__ import annotations to enable this postponed annotation evaluation that we see in the initial comment. Pylance seems to stop complaining.
  • If you are using Python 3.11+, you can use the typing.Self type.

See https://stackoverflow.com/questions/33533148/how-do-i-type-hint-a-method-with-the-type-of-the-enclosing-class/33533514#33533514 for more detail.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants