Skip to content

mypy infers the wrong type for classmethods #3482

Open

Description

@carljm

We have some code that simplifies to this:

class A:
    @classmethod
    def hi(cls):
        pass

    bye = classmethod(hi.__func__)

(The real code is wrapping an async classmethod with a sync version; there's another async-to-sync wrapper in there.)

Mypy doesn't like this code because it doesn't know that classmethods have a __func__ attribute. The typeshed annotation for classmethod includes __func__, but mypy doesn't infer the real classmethod type for hi (which is the actual type at runtime), it just infers a general callable type.

This may not be easily fixed until we have protocol support and can more easily have various callable subtypes?

I'm also OK if this is closed as "just use cast() if you're accessing private attributes of a classmethod"; it's certainly not high priority.

Activity

  1. refi64 commented on Jun 1, 2017

    @refi64
    Contributor

    I think the root cause of this is roughly the same as #2267: descriptors are treated as callables inside the class definition.

  2. gvanrossum commented on Jun 1, 2017

    @gvanrossum
    Member

    Yeah, mypy needs to be much more careful with these things.

  3. changed the title [-]mypy doesn't know that classmethods have a __func__ attribute[/-] [+]mypy infers the wrong type for classmethods[/+] on Jun 23, 2017
  4. ilevkivskyi commented on Dec 20, 2019

    @ilevkivskyi
    Member

    Note that this also applies to static methods, see for example #8181

  5. added
    bugmypy got something wrong
    topic-runtime-semanticsmypy doesn't model runtime semantics correctly
    topic-descriptorsProperties, class vs. instance attributes
    on Mar 28, 2022
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

    bugmypy got something wrongtopic-descriptorsProperties, class vs. instance attributestopic-runtime-semanticsmypy doesn't model runtime semantics correctly

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions