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)
|