Skip to content

Unable to assign a function a method #2427

Closed
@rowillia

Description

@rowillia

For example:

from typing import Any, Optional


class Foo(object):
    def __init__(self):
        # type: () -> None
        self.x = 0

    def get_x(self, a=None, b=None):
        # type: (Optional[int], Optional[int]) -> int
        return self.x + (a or 0) + (b or 0)


def get_x_patch(self, *args, **kwargs):
    #  type: (Foo, *Any, **Any) -> int
    return 42


Foo.get_x = get_x_patch

Results:

test_method_assignment.py:19: error: Cannot assign to a method

This assignment should be legal as any call to get_x will be able to call get_x_patch. It looks like 3ce8d6a explicitly disallowed all method assignments, but there's not a ton of context behind it.

I know monkeypatching is generally frowned upon, but is unfortunately a very popular part of Python. I can always mark those lines as ignored, but I'd rather be able to test that the patch is compatible with the underlying method with mypy.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions