8000 No warning for uninitialised instance variable when using instance variable annotation · Issue #4206 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content

No warning for uninitialised instance variable when using instance variable annotation #4206

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

Closed
ned opened this issue Nov 4, 2017 · 1 comment

Comments

@ned
Copy link
ned commented Nov 4, 2017

If you intend to initialise an instance variable in __init__ but forget to do so, mypy won't warn if PEP 526 style instance variable annotation is used. For example, the following code emits a runtime warning but no warning from mypy. Tested on mypy version 0.540.

class MyClass:
    my_attr: str
    def __init__(self, my_attr: str) -> None:
        pass
        # missing line: self.my_attr = my_attr

x = MyClass("grapefruit")
s: str = x.my_attr
#          ^ AttributeError at runtime

However, if the instance variable annotation is removed, mypy does warn.

class MyClass:
    def __init__(self, my_attr: str) -> None:
        pass
        # missing line: self.my_attr = my_attr

x = MyClass("grapefruit")
s: str = x.my_attr

From PEP 526 (emphasis mine):

In particular, the value-less notation a: int allows one to annotate instance variables that should be initialized in __init__ or __new__.

@emmatyping
Copy link
Member

Duplicate of #4019

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

2 participants
0