python / python/mypy

Confusing error message when assigning to `SomeType.__class__`

Open
#13,025 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-descriptors topic-runtime-semantics
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

class X:
    pass

X.__class__ = type
# Cannot assign to a method
# Incompatible types in assignment (expression has type "Type[type]", variable has type overloaded function)

Bug Report
X.__class__ isnt an overloaded function nor method, it is property defined in object class:

>>> object.__dict__['__class__']
<attribute '__class__' of 'object' objects>

Expected Behavior
I expect to get something like this:
Incompatible types in assignment (expression has type "type[type]", variable has type "type[type[X]]")
or
"X.__class__" doesnt support assignment
or
Cannot determine type of "X" after ".__class__" assignment
or
Cannot change type of class "X"

With variables it gives good error message:

class X: pass
class Y: pass
x = X()
x.__class__ = Y # Incompatible types in assignment (expression has type "Type[Y]", variable has type "Type[X]")

My Environment

  • mypy 0.961 (compiled: no)
  • no command-line flags, no config file
  • CPython 3.10.4
  • Windows 10

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the minimal class-assignment reproduction in the report and compare it with the instance-assignment example. Trace mypy's handling of __class__ assignment and ensure the class case produces a type-specific or clearly unsupported-assignment diagnostic without misidentifying __class__ as a method.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.