deshaw / pyflyby

A set of productivity tools for Python
https://deshaw.github.io/pyflyby/
Other
352 stars 52 forks source link

False positive of undefined name `__class__` when running `tidy-imports` #325

Closed Atry closed 6 months ago

Atry commented 6 months ago

Given the following file:

# a.py
class MyClass:
    def get_class(self):
        return __class__

When running

tidy-imports --replace a.py

I got the following error

[PYFLYBY] /home/nixos/peftai/a.py:4: undefined name '__class__' and no known import for it

I think the error message is a false positive.

Version information

tidy-imports --version
pyflyby 1.9.2 (tidy-imports)
Carreau commented 6 months ago

Do you really want to use __class__, or did you meant self.__class__? The bare __class__ closure is rarely used in instance methods AFAICT, and I'm wondering if it is explicitly not added to pyflyby codebase to detect this.

Atry commented 6 months ago

__class__ is useful in @staticmethod-decorated functions.

class MyClass:
   _MY_REGEX: ClassVar = re.compile(r"[^\w]")
   @staticmethod
   def my_static_function(s: str):
     return re.sub(__class__._MY_REGEX, "_", s)
Carreau commented 6 months ago

Sure, yes, I understand the need for it in __new__, static methods and other context, I was just checking for the use case you posted. One could also argue that if you need __class__ in a static method, then maybe it should be a class method as well, and you should refer to cls._MY_REGEX.

Atry commented 6 months ago

Sometime you want the class where the method is defined, not the final class being instantiated. For example: https://stackoverflow.com/a/78306250/955091