Skip to content

"Local variable (defined in enclosing scope) referenced before assignment" wording is misleading #390

Open

Description

@mhsmith
def f():
    x = None
    def g():
        # Programmer forgot to add `nonlocal` here.
        if x is None:
            x = "hello"

foo.py:5:12: F823 local variable 'x' (defined in enclosing scope on line 2) referenced before assignment

But it's not the variable defined on line 2 which is being referenced before assignment, it's the one defined on line 6. The programmer thinks they're using the one on line 2, and the message only reinforces their mistake.

Suggest rephrase to something like (shadowing name from line 2 in enclosing scope).

(There's a similar example in #315 where the enclosing scope was global.)

Activity

  1. ankitxjoshi commented on Jan 2, 2019

    @ankitxjoshi
    Contributor

    Yes. It does seems to create misunderstanding.

  2. vdumchiviy commented on May 2, 2022

    @vdumchiviy

    I want to add some example:

    from mymodule import my_data
    
    @pytest.mark.asyncio
    @pytest.mark.database
    @pytest.mark.isolated
    async def test_1(
    ) -> None:
        my_data_usage = deepcopy(my_data)
        #  SOME CODE HERE
        my_data = something.json()
        assert all(_ in my_data["property"] for _ in ["https", "jpg"])`
    
    
    

    I got this message: "local variable 'my_data' defined in enclosing scope on line 1 referenced before assignment" flake8(F823) [Ln 8 Col 30]
    But problem is on the last 2 rows (approx 20 rows from line 8). I faced with this problem due to refactoring my code, so it confused me a bit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions