python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.46k stars 2.83k forks source link

Mypy doesn't understand __class__ #4177

Open dmcooke opened 7 years ago

dmcooke commented 7 years ago

Consider the following (Python 3, of course)

from typing import Any

class Foo:
    def foo(self, x:Any) -> bool:
        return isinstance(x, __class__)

mypy gives the following error:

x.py:5: error: Name '__class__' is not defined

It should assume __class__ to be Foo (as per the language documentation).

I usually work around this by adding

if TYPE_CHECKING:
    __class__ : Type

at the top of files that use __class__, but that's not ideal.

gvanrossum commented 7 years ago

Why are you using the __class__ cell? While it is indeed documented, it's really just meant as a hack so that argument-less super() can find the current class; other use cases are pretty esoteric IMO. Unless you have a particularly bad habit of frequently renaming your classes you're better off just naming the class explicitly (always assuming that self.__class__ doesn't do it for you).

dmcooke commented 7 years ago

I prefer it to using the name, as __class__ is determined by the lexical scope, whereas by name is by the dynamic scope. I am probably overusing it, but it does give a measure of safety with regards to renaming or assigning something else to the class name (such as the somewhat common practice of making singletons by Foo = Foo()).

Regardless, still a bug (either in mypy, or the Python documentation).

elazarg commented 7 years ago

There are two items here:

gvanrossum commented 7 years ago

whereas by name is by the dynamic scope

Not sure what you mean by "dynamic scope" here -- certainly the call site doesn't enter into it.

Anyway, this is a low priority feature request. (I count the mere presence of __class__ a feature request -- adding it to typeshed isn't enough since it is only defined inside a class.

antoscha commented 3 years ago

Are there any news on that?

JelleZijlstra commented 3 years ago

Doesn't look like it! If you care about this issue, feel free to submit a PR; it's unlikely to be picked up by a core team member any time soon.