What is the disadvantage of using the .__ new__ object in __new__?

Coding exception codes, I came across this error:

TypeError: object.__new__(A) is not safe, use Exception.__new__()

There is a similar question here: TypeError: object .__ new __ (int) is not safe, use int .__ new __ () . Therefore, it is __new__deprecated for the following reason:

[Python-Dev] __new__deprecation

Guido van Rossum

"A message means only what he says. :-) It makes no sense to call object.__new__()with more than a class parameter and any code that is just dumping these args into a black hole."

But the warning in 3.3 that I get "unsafe" is scary. I am trying to understand the meaning of use object.__new__, consider this example:

>>> class A(Exception):
...     def __new__(cls, *args):
...             return object.__new__(A)
...
>>> A()
TypeError: object.__new__(A) is not safe, use Exception.__new__()

Unsuccessfully. Another example:

>>> class A(object):
...     def __new__(cls, *args):
...             return object.__new__(A)
...
>>>
>>> A()
<__main__.A object at 0x0000000002F2E278>

. object , Exception , , . Exception, TypeError, object, ?

(a) object.__new__, Python (TypeError:...is not safe...) ?

(b) Python __new__? : , Python ?

+4
2

object.__new__, Exception.__new__.

Exception , , __new__ , , .

, . Python , .

:

class A(object):
    def __new__(cls):
        rtn = object.__new__(cls)
        rtn.new_called = True
        return rtn

    def __init__(self):
        assert getattr(self,'new_called',False), \
            "object.__new__ is unsafe, use A.__new__"

class B(A):
    def __new__(cls):
        return object.__new__(cls)

:

>>> A()
<__main__.A object at 0x00000000025CFF98>

>>> B()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in __init__
AssertionError: object.__new__ is unsafe, use A.__new__

:

>>> class A(Exception):
...     def __new__(cls, *args):
...             return object.__new__(A)

-, __new__ object, Exception.__new__.

, , A __new__ cls, , A.

. :

class A(object):
    def __new__(cls):
        return object.__new__(A)  # The same erroneous line, without Exception

class B(A):
    pass

B() B:

>>> B()
<__main__.A object at 0x00000000025D30B8>
+2

object.__new__(A) A, Exception.__new__(), .

0

Source: https://habr.com/ru/post/1654721/


All Articles