Title: PEP 695 variance inference treats a writable Callable[[T], None] attribute as contravariant. · Issue #22339 · python/mypy · GitHub
Open Graph Title: PEP 695 variance inference treats a writable Callable[[T], None] attribute as contravariant. · Issue #22339 · python/mypy
X Title: PEP 695 variance inference treats a writable Callable[[T], None] attribute as contravariant. · Issue #22339 · python/mypy
Description: Bug Report When a class uses PEP 695 syntax, infer_variance infers T as contravariant when T appears as the parameter of a Callable stored in a public, writable attribute (self.cb: Callable[[T], None]). While the typing spec's variance i...
Open Graph Description: Bug Report When a class uses PEP 695 syntax, infer_variance infers T as contravariant when T appears as the parameter of a Callable stored in a public, writable attribute (self.cb: Callable[[T], No...
X Description: Bug Report When a class uses PEP 695 syntax, infer_variance infers T as contravariant when T appears as the parameter of a Callable stored in a public, writable attribute (self.cb: Callable[[T], No...
Opengraph URL: https://github.com/python/mypy/issues/22339
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"PEP 695 variance inference treats a writable Callable[[T], None] attribute as contravariant.","articleBody":"### Bug Report\n\nWhen a class uses PEP 695 syntax, `infer_variance` infers `T` as contravariant when `T` appears as the parameter of a `Callable` stored in a public, writable attribute (`self.cb: Callable[[T], None]`).\n\nWhile the typing spec's variance inference section doesn't explicitly mention mutable attributes, this seems inconsistent with how mypy handles mutability elsewhere:\n1. Mypy infers writable `T` and `Callable[[], T]` attributes in PEP 695 classes as invariant (and the docs note that a public, mutable attribute makes a class invariant unless `_`-prefixed or `Final`).\n2. Mypy's protocol checker treats the exact same attribute shape as invariant (`class P(Protocol[T_contra]): cb: Callable[[T_contra], None]` fails with `Contravariant type variable \"T_contra\" used in protocol where invariant one is expected`).\n\nBecause `Handler[T]` is inferred as contravariant, mypy allows passing `Handler[Animal]` where `Handler[Dog]` is expected, leading to a runtime `AttributeError` when the callback is reassigned.\n\n### To Reproduce\n\n```python\nfrom collections.abc import Callable\n\nclass Animal: ...\nclass Dog(Animal):\n def bark(self) -> None: print(\"woof\")\nclass Cat(Animal): ...\n\nclass Handler[T]:\n def __init__(self, cb: Callable[[T], None]) -> None:\n self.cb = cb\n\ndef use(h: Handler[Dog]) -> None:\n h.cb = lambda d: d.bark()\n\nha = Handler[Animal](lambda a: print(a))\nuse(ha) # mypy: no error (Handler[Animal] accepted as Handler[Dog])\nha.cb(Cat()) # Runtime: AttributeError: 'Cat' object has no attribute 'bark'\n```\n\n**Playground link:** https://mypy-play.net/?gist=02b87ea41dc199ac0c8504d9e14d75d8\n\nThe same behavior occurs with a class-body annotation (`cb: Callable[[T], None]`), a plain `def` instead of a `lambda`, a property with a setter, and a `@dataclass` field. Control cases (`Final`, read-only `@property`, and `_cb` underscore prefix) remain contravariant as expected.\n\n### Expected Behavior\n\n`Handler[T]` should be inferred as invariant in `T`, rejecting `use(ha)` with:\n```text\nerror: Argument 1 to \"use\" has incompatible type \"Handler[Animal]\"; expected \"Handler[Dog]\" [arg-type]\n```\n(Both `pyright` and `ty` infer `Handler[T]` as invariant here and reject the call.)\n\n### Actual Behavior\n\n```text\nSuccess: no issues found in 1 source file\n```\n(Swapping the direction -- passing `Handler[Dog]` to `Handler[Animal]` -- is rejected, confirming `T` is inferred as contravariant rather than bivariant.)\n\n### Possible Cause\n\nIn `infer_variance` (`mypy/subtypes.py`), the `settable` check is only applied in the covariant branch:\n\n```python\nif not is_subtype(typ, typ2):\n co = False\n # missing: if settable: contra = False\nif not is_subtype(typ2, typ):\n contra = False\n if settable:\n co = False\n```\n\nAdding `if settable: contra = False` to the first branch makes the class invariant (while preserving the `_` prefix exemption, `Final`, and read-only properties) and passes the local `testcheck`, `testtypes`, and `testsubtypes` suites on master, though I haven't measured potential fallout via `mypy_primer`.\n\n(Note: `@dataclass` fields with `Callable` types also require checking `v.is_settable_property` in `get_member_flags`, since `_propertize_callables` in the dataclass plugin converts callable fields into properties, which currently drops `IS_SETTABLE`).\n\nHappy to open a PR with a test in `check-python312.test` if this change is desirable. (Disclosure: found via differential testing; used an LLM to assist with source navigation).\n\n### My Environment\n\n- Mypy version used: 2.4.1 and master (`934e703a8`)\n- Mypy command-line flags: `--python-version 3.13 --check-untyped-defs --show-error-codes --no-incremental`\n- Mypy configuration options from `mypy.ini` (and other config files): None\n- Python version used: 3.13.15","author":{"url":"https://github.com/DerekLaymn","@type":"Person","name":"DerekLaymn"},"datePublished":"2026-10-31T19:43:19Z","url":"https://github.com/python/mypy/issues/22339"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:6364fceb-362a-3254-cd9b-28d436a54979 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | BA8A:3CE430:2032B8:2D174E:6B00581A |
| html-safe-nonce | c9225dc509151061d11541900cdb3636c81d396feab7ead51a8f7be4a7cf43f6 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCQThBOjNDRTQzMDoyMDMyQjg6MkQxNzRFOjZCMDA1ODFBIiwidmlzaXRvcl9pZCI6IjE0ODc1MzcxOTQzNDMwOTQyOTgiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | fe3e996b14af5a73825355b14d712beb0db078afe567e7e34249254c79682625 |
| hovercard-subject-tag | issue:6139025687 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/mypy/22339/issue_layout |
| twitter:image | https://opengraph.githubassets.com/35dc5ed93c8579226a841f775eb7b24e7402ba313aa7b8abd687a82055009f22/python/mypy/issues/22339 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/35dc5ed93c8579226a841f775eb7b24e7402ba313aa7b8abd687a82055009f22/python/mypy/issues/22339 |
| og:image:alt | Bug Report When a class uses PEP 695 syntax, infer_variance infers T as contravariant when T appears as the parameter of a Callable stored in a public, writable attribute (self.cb: Callable[[T], No... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | DerekLaymn |
| hostname | github.com |
| expected-hostname | github.com |
| None | 29be975efff6507a5d135de9c7d634cf7ff8f0c55222a64386ab3202209aaf73 |
| turbo-cache-control | no-preview |
| go-import | github.com/python/mypy git https://github.com/python/mypy.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 7053637 |
| octolytics-dimension-repository_nwo | python/mypy |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 7053637 |
| octolytics-dimension-repository_network_root_nwo | python/mypy |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | eacd927ba6112e3b01ba99c762bd699a4a4f5df7 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width