Closed nqhq-lou closed 11 months ago
If you run the code in your example, you will receive a runtime exception from Python ("NameError: name 'MyClass' is not defined"). Pylance is warning you that your code will crash, so it's correct in generating an error here.
If you want to use a not-yet-declared identifier in a type annotation, you can do one of two things:
Enclose the type annotation in quotes.
class MyClass:
def __init__(self):
pass
def myfunc(self) -> "MyClass":
return self
from __future__ import annotations
to the top of your file. This tells the Python interpreter to defer evaluation of your annotations.
from __future__ import annotations
class MyClass: def init(self): pass
def myfunc(self) -> MyClass:
return self
If you run the code in your example, you will receive a runtime exception from Python ("NameError: name 'MyClass' is not defined"). Pylance is warning you that your code will crash, so it's correct in generating an error here.
If you want to use a not-yet-declared identifier in a type annotation, you can do one of two things:
- Enclose the type annotation in quotes.
class MyClass: def __init__(self): pass def myfunc(self) -> "MyClass": return self
- Add a
from __future__ import annotations
to the top of your file. This tells the Python interpreter to defer evaluation of your annotations.from __future__ import annotations class MyClass: def __init__(self): pass def myfunc(self) -> MyClass: return self
Thanks! My question is solve:D
Environment data
Code Snippet
Expected behavior
Pylance should not report an undefined variable error for a class method that returns an instance of the same class.
Actual behavior
Pylance reports an undefined variable error for a class method that returns an instance of the same class.
Logs