This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: AttributeError from type annotation
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.8, Python 3.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: eric.smith, levkivskyi, robieta
Priority: normal Keywords:

Created on 2020-05-11 17:19 by robieta, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (4)
msg368635 - (view) Author: Taylor Robie (robieta) Date: 2020-05-11 17:19
Consider the following:
```
import re

class MyClass(object):
    def re(self):
        pass

    def foo(self, m: re.Match):
        pass
```

Even though `re` and `MyClass.re` are distinct namespaces, the type annotation misses that fact (presumably there is an issue with how it is parsing the AST) and attempts to access MyClass.re.Match, resulting in:

`AttributeError: 'function' object has no attribute 'Match'`

Commenting out the definition of `MyClass.re` or reversing the definition order resolves the issue.
msg368640 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2020-05-11 18:52
This is not an annotations-only issue. This is no different from:


import re

class MyClass(object):
    def re(self):
        pass

    m = re.Match

Which gives the same error. It's being evaluated at class scope.
msg368644 - (view) Author: Taylor Robie (robieta) Date: 2020-05-11 19:19
Ah, I see. If this is intended behavior (which is sounds like it is?) feel free to close. Thanks!
msg368972 - (view) Author: Ivan Levkivskyi (levkivskyi) * (Python committer) Date: 2020-05-15 20:48
Yes, this is as expected. A recommended workaround is to define a type alias like `Match = re.Match` before the class body. You can also suppress the exception with `from __future__ import annotations` (so that the annotations are not evaluated), but static type checkers like mypy will still force you to use the alias.
History
Date User Action Args
2022-04-11 14:59:30adminsetgithub: 84775
2020-05-15 20:48:00levkivskyisetstatus: open -> closed

nosy: + levkivskyi
messages: + msg368972

resolution: not a bug
stage: resolved
2020-05-11 19:19:25robietasetmessages: + msg368644
2020-05-11 18:52:38eric.smithsetnosy: + eric.smith
messages: + msg368640
2020-05-11 17:19:58robietacreate