New submission from Serhiy Storchaka <storchaka+cpyt...@gmail.com>:

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)

----------
components: Interpreter Core
messages: 363664
nosy: gvanrossum, serhiy.storchaka
priority: normal
severity: normal
status: open
title: Move handling of one-argument call of type() from type.__new__() to 
type.__call__()
versions: Python 3.9

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue39904>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to