Skip to content

MyPy does not recognize methods as MethodType, only as Callable #19620

@chopan050

Description

@chopan050

Bug Report

TL;DR: MyPy only recognizes methods as Callable, not as actual methods (MethodType) with __func__ and __self__ attributes.


Define the following:

from types import MethodType

class Foo:
    def some_method(self):
        print("Hi")

Then

isinstance(Foo().some_method, MethodType)

returns True, and

hasattr(Foo().some_method, "__func__") and hasattr(Foo().some_method, "__self__")

also returns True. Printing

print(Foo().some_method.__func__)
print(Foo().some_method.__self__)

shows <function Foo.some_method at [address]> and <__main__.Foo object at [address]>, respectively.


However, when passing the following code to MyPy:

def my_function(method: MethodType) -> None:
    print(method.__func__)

my_function(Foo().some_method)

it fails with error: Argument 1 to "my_function" has incompatible type "Callable[[], Any]"; expected "MethodType" [arg-type]. Plus, when passing

print(Foo().some_method.__func__)
print(Foo().some_method.__self__)

it fails with error: "Callable[[], Any]" has no attribute "__func__" [attr-defined] and error: "Callable[[], Any]" has no attribute "__self__" [attr-defined].

To Reproduce

https://gist.github.com/mypy-play/502584d664add2f745c9ed1f6334c7ee

Expected Behavior

I expected that MyPy recognized Foo().some_method as a MethodType with __func__ and __self__ attributes.

Actual Behavior

MyPy didn't recognize the method as a MethodType. The output is above.

Your Environment

  • Mypy version used: 1.17.0
  • Mypy command-line flags: None (all options disabled by default on mypy-play.net)
  • Mypy configuration options from mypy.ini (and other config files): The default used by mypy-play.net
  • Python version used: 3.13

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-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