Improve error message for return in metaclass __new__()
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
Feature or enhancement
Proposal:
Case1: When overriding new in a custom Meta class and forgetting to return a class object (e.g. by omitting return super().new(..)) Python raises the following error:
TypeError: 'NoneType' object is not callable
Case2: When returning something else other than class object it raises following error:
TypeError: 'str' object is not callable
This messages, while technically correct, lacks guidance for common scenarios and can confuse developers - especially those new to Meta class.
Steps to Reproduce:
Case1:
class NewMeta(type):
def new(cls, name, bases, dct):
print ("Forgot to return!")
class MyClass(metaclass = NewMeta):
def greet(self):
pass
m = MyClass()
Output: TypeError: 'NoneType' object is not callable
Case2:
class NewMeta(type):
def new(cls, name, bases, dct):
return ("Return non-callable object")
class MyClass(metaclass = NewMeta):
def greet(self):
pass
m = MyClass()
Output: TypeError: 'str' object is not callable
Suggested Improvement:
Improve the error message to something like:
TypeError: metaclass new must return a class object. Recommendation: super().new(metacls, name, bases, namespace)?
This small change could save significant debugging time and make advanced features like metaclasses more approachable.
Python Version:
Tested in Python 3.12.4 (tags/v3.12.4:8e8a4ba, Jun 6 2024, 19:30:16) [MSC v.1940 64 bit (AMD64)]
Why This Matters:
- Metaclass usage is already an advanced topic.
- Improving the DX (developer experience) here will help advanced learners and reduce friction.
- Similar improvements have already been adopted in recent Python versions for other common errors.
Has this already been discussed elsewhere?
This is a minor feature, which does not need previous discussion elsewhere
Links to previous discussion of this feature:
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing both metaclass new cases described in the issue and trace the runtime entry point that raises the current TypeError. Update the diagnostics for a missing or non-class return, then add coverage for both examples and verify the messages clearly explain the required return value.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100