python / python/mypy

false positive "name not defined" with list comprehension in function arguments default value

Open
#9,346 6 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug priority-1-normal
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

  • Are you reporting a bug, or opening a feature request?

This is a bug I believe

  • Please insert below the code you are checking with mypy
def a():
  pass

def b(
    bb=[list_comprehension_argument for list_comprehension_argument in "abc" 
          if list_comprehension_argument]
  ):
  pass
  • What is the actual behavior/output?
mypy repro.py
repro.py:5: error: Name 'list_comprehension_argument' is not defined
repro.py:6: error: Name 'list_comprehension_argument' is not defined
Found 2 errors in 1 file (checked 1 source file)
  • What is the behavior/output you expect?

I believe there should be no error reported.

  • What are the versions of mypy and Python you are using?
    Do you see the same issue after installing mypy from Git master?

this is on mypy from git master, mypy 0.790+dev.2b704df25ca299e6936927be8d41d2ab945cee2a

  • What are the mypy flags you are using? (For example --strict-optional)

This is using the default flags.


This only seem to happens if there's another function like this one, before the function with list comprehension in arguments:

def a():
  pass

When removing this other function or putting it after the one with list comprehension in argument, this false positive is not reported, I mean no error are reported for:

def b(
    bb=[list_comprehension_argument for list_comprehension_argument in "abc" 
          if list_comprehension_argument]
  ):
  pass

def a():
  pass

or

def b(
    bb=[list_comprehension_argument for list_comprehension_argument in "abc" 
          if list_comprehension_argument]
  ):
  pass

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the report by running mypy repro.py with the shown function-order variants on the referenced git-master version. Trace handling for function argument defaults and list-comprehension scopes, then add a regression test covering both orderings; done means no false-positive name errors and the existing suite passes.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.