This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Incorrect error message on invalid __class__ assignments
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: ppperry, steven.daprano, xiang.zhang
Priority: normal Keywords:

Created on 2017-03-11 16:00 by ppperry, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (2)
msg289448 - (view) Author: (ppperry) Date: 2017-03-11 16:00
If you try to set the __class__ of a type which doesn't support "__class__" assignments, you get the error message:

    TypeError: __class__ assignment only supported for heap types or ModuleType subclasses

However, the actual restriction doesn't require a subclass of "ModuleType"; the below code works:

    import random
    class M(type(random)):pass
    random.__class__ = M

Thus the error message is incorrect.
msg289463 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2017-03-12 02:15
Your example works because random is a module:

py> from types import ModuleType
py> import random
py> type(random) is ModuleType
True

Since random is an instance of ModuleType, your class M is a subclass of ModuleType, and assigning to random.__class__ is allowed.

I'm closing this issue, but if can demonstrate an actual problem, please feel free to re-open it.
History
Date User Action Args
2022-04-11 14:58:44adminsetgithub: 73980
2017-03-12 02:15:13steven.dapranosetstatus: open -> closed

nosy: + steven.daprano
messages: + msg289463

resolution: not a bug
stage: resolved
2017-03-11 16:25:59xiang.zhangsetnosy: + xiang.zhang
2017-03-11 16:00:21ppperrycreate