pyflakes: Undefined name error for unimported type hints written as string

PEP484 explicitly allows unimported types to be specified as a string. pyflakes 2.0.0 tries to parse these strings and is unable to find the correct typedefs and reports an unexpected error.

def hello(a: "Unknown") -> str:
    return str(a)

generates the pyflakes error

foo.py:1: undefined name 'Unknown'

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 9
  • Comments: 16 (11 by maintainers)

Commits related to this issue

Most upvoted comments

Annotations do not have to be used for type hints though. They were introduced in PEP 3107.

These annotation consumers can do anything they want with a function’s annotations. For example, one library might use string-based annotations to provide improved help messages, like so:

Pyflakes should not require them to be type hints.

is anything done to fix this?

I currently use typing however cannot import the annotated type as it will give a circular import creating a whole new range of bugs. That might be a symbol of some bad software design on my end (not sure) but it’s problematic to add NOQA to multiple function definitions in my django application

what about the usual “import for type annotations” approach:

if False:  # if typing.TYPE_CHECKING if you don't care about 3.5.0 / 3.5.1
    import accounts.models

def get_upcoming_deposits(self, user: "accounts.models.User"): ...

Can you use the mypy only import?

if False:  # or typing.TYPE_CHECKING  if python3.5.3+
    from ...

Though circular imports are often an indication of a design problem