-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
mypy complains about monkey-patching classes in another module #1152
Comments
Can you give an example where replacing a function fails? Some kinds of function monkey patching should work, and it would be nice to have an example that is still broken. In general, type checking the compatibility of classes is hard, but at least these should be fixed to work:
This is a little trickier:
|
Hmm I can't reproduce the function issue so let's remove that from this issue for now; I'll open another if I can reproduce. |
General suggestion: can you copy/paste the exact error message(s) you got from mypy? Those are often invaluable hints for finding the root of the problem (and figuring out how to run mypy on exactly the code you were using takes much longer). |
Oops, yeah, sorry about that, this is the error:
|
Mypy doesn't support this kind of conditional declaration based on catching ImportError. See mypy issue #1152 (python/mypy#1152) for more information.
Here's a complete example which should probably not generate an error: # main.py
from typing import Any
import m
def f(x: Any) -> None:
m.C = x # Cannot assign to a type # m.py
class C: pass |
I've tried this method to change/enhance the types of attributes for a class from an external module this way. # m.py
class C: pass from typing import cast
import m
class TypedC:
typed_attr: str
m.C = TypedC # Cannot assign to a type
m.C = cast(TypedC, m.C) # Cannot assign to a type
# works - a bit surprising (you might expect this to e.g. use `Any` then).
m.C = TypedC # type: ignore (Using |
I'm fine with mypy complaining about this. Monkeypatching classes is unsound given nominal typing. |
This issue affects unannotated code. Here's some example code from https://github.com/zulip/zulip/blob/master/zerver/lib/test_helpers.py#L47:
(There's a similar issue with replacing a function rather than a class; and an example a few lines down in the Zulip codebase)
The text was updated successfully, but these errors were encountered: