Title: AttributeError from type annotation
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.8, Python 3.7
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 2020-05-15 20:48 by levkivskyi. 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):

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

Even though `re` and `` 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, resulting in:

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

Commenting out the definition of `` 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):

    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.
Date User Action Args
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