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.

Author serhiy.storchaka
Recipients gvanrossum, serhiy.storchaka
Date 2020-03-08.14:43:00
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1583678581.12.0.621267485575.issue39904@roundup.psfhosted.org>
In-reply-to
Content
The builtin type() serves two functions:

1. When called with a single positional argument it returns the type of the argument.

>>> type(1)
<class 'int'>

2. Otherwise it acts as any class when called -- creates an instance of this class (a type). It includes calling corresponding __new__ and __init__ methods.

>>> type('A', (str,), {'foo': lambda self: len(self)})
<class '__main__.A'>

type is a class, and it can be subclassed. Subclasses of type serve only the latter function (the former was forbidden in issue27157).

>>> class T(type): pass
... 
>>> T(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type.__new__() takes exactly 3 arguments (1 given)
>>> T('A', (str,), {'foo': lambda self: len(self)})
<class '__main__.A'>

But surprisingly you can use the __new__ method for getting the type of the object.

>>> type.__new__(type, 1)
<class 'int'>
>>> T.__new__(T, 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type.__new__() takes exactly 3 arguments (1 given)

The proposed PR moves handling the special case of one-argument type() from type.__new__ to type.__call__.

It does not fix any real bug, it does not add significant performance boost, it does not remove a lot of code, it just makes the code slightly more straightforward. It changes the behavior of type.__new__(type, obj) which is very unlikely called directly in real code.

>>> type(1)
<class 'int'>
>>> type.__new__(type, 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type.__new__() takes exactly 3 arguments (1 given)
History
Date User Action Args
2020-03-08 14:43:01serhiy.storchakasetrecipients: + serhiy.storchaka, gvanrossum
2020-03-08 14:43:01serhiy.storchakasetmessageid: <1583678581.12.0.621267485575.issue39904@roundup.psfhosted.org>
2020-03-08 14:43:01serhiy.storchakalinkissue39904 messages
2020-03-08 14:43:00serhiy.storchakacreate