[docs] [issue17179] Misleading error from type() when passing unknown keyword argument

Nick Coghlan report at bugs.python.org
Sat Feb 16 06:05:12 CET 2013


Nick Coghlan added the comment:

The types.new_class docs are quite clear that the supplied keyword arguments are equivalent to those provided in the type header (if you want to pre-populate the namespace, that's what exec_body is for). The problem here is that the dual signature of type (retrieving the type of an existing object, or creating a new one), and the fact that type.__prepare__ ignores all arguments, means the error message is thoroughly misleading when you pass an unknown keyword argument:

>>> type.__prepare__(foo=1)
{}
>>> type("Example", (), {}, foo=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type() takes 1 or 3 arguments

>>> class Example(foo=1): pass
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type() takes 1 or 3 arguments

>>> import types
>>> types.new_class("Example", (), dict(foo=1))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/ncoghlan/devel/py3k/Lib/types.py", line 52, in new_class
    return meta(name, bases, ns, **kwds)
TypeError: type() takes 1 or 3 arguments

The reason type.__prepare__ ignores its arguments is to make it easy for people to use type to anchor a custom metaclass hierarchy and call super().__prepare__(name, bases, **kwds) without needing to worry much about filtering the keyword arguments. (The class machinery intercepts the metaclass hint and never passes it to __prepare__ or the metaclass constructor).

That means the real change needed here is to update type's error message for bad arguments to properly report unknown keyword errors when using the PEP 3115 metaclass API.

----------
assignee:  -> docs at python
components: +Documentation
nosy: +docs at python
title: Incorrect use of type function in types.new_class -> Misleading error from type() when passing unknown keyword argument

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue17179>
_______________________________________


More information about the docs mailing list