PyCQA / pyflakes

A simple program which checks Python source files for errors
https://pypi.org/project/pyflakes
MIT License
1.37k stars 178 forks source link

F821 undefined name 'something' when using __getitem__ #809

Closed hc closed 6 months ago

hc commented 6 months ago

Here an example that raises a F821 error:

class Something:
    def __getitem__(self, ok):
        return Something()

Something_ = Something()

def somefunction(arg1, arg2):
    return int

my_variable: Something_[somefunction("something", 10)] = None

The error is then F821 undefined name 'something'

Is there any workaround (without disabling F821 on that specific line) or way to improve that particular scenario?

asottile commented 6 months ago

you should use Annotated if you are using non pep 484 types as annotations

hc commented 6 months ago

How that would look like in the example above with Annotated?

asottile commented 6 months ago

what have you tried? the docs for Annotated are fairly straightforward

hc commented 6 months ago

This is a fairly big codebase, so I am looking for what we could update with minimum change to make it passes these checks

asottile commented 6 months ago

can you show me your attempt to use Annotated? I'm not sure what you're confused about so I can't help you unless you show me

hc commented 6 months ago

Sure, trying different scenario with:

from typing import Annotated
from typing import Annotated as Aliased1

def somefunction(a, b):
    return str

Aliased2 = Annotated

annoted: Annotated[int, somefunction(-10, "ok")] = None

annoted2: Aliased1[int, somefunction(-10, "ok")] = None

annoted3: Aliased2[int, somefunction(-10, "ok")] = None

As we rely on custom alias (and not just Annotated) with this the first one works with Annotated, by the Aliased1 and Aliased2 raise F821

asottile commented 6 months ago

that's a completely different problem than your issue and has several duplicates if you search around

hc commented 6 months ago

Based on my initial example, what it would look like then using Annotated?

asottile commented 6 months ago

@hc what have you tried?