Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does __init__ not get called if __new__ called with no args

Tags:

python

I am trying to create (not exactly restore) an object which has its attributes saved in a database. Therefore, I do not want to call __init__. This desire appears to be inline with Guido's intended use for __new__. I do not understand why __init__ is not getting called.

Take the following snippet for example, it returns an instance of class User without calling __init__.

class User(object):
    def __init__(self, arg1, arg2):
        raise Exception

user = User.__new__(User)

print user
<project.models.User object at 0x9e2dfac>

This is the exact behavior I want. However, my question is that I do not understand why?

According to the python docs __init__ is supposed to be called when __new__ "returns an instance of cls."

So why is __init__ not being even called, even though __new__ returns a class instance?

like image 874
Bobby Chambers Avatar asked Aug 01 '11 19:08

Bobby Chambers


2 Answers

The constructor (User()) is responsible for calling the allocator (User.__new__()) and the initializer (User.__init__()) in turn. Since the constructor is never invoked, the initializer is never called.

like image 160
Ignacio Vazquez-Abrams Avatar answered Nov 04 '22 11:11

Ignacio Vazquez-Abrams


Because you're bypassing the usual construction mechanism, by calling __new__ directly. The __init__-after-__new__ logic is in type.__call__ (in CPython see typeobject.c, type_call function), so it happens only when you'd do User(...).

like image 22
Cat Plus Plus Avatar answered Nov 04 '22 10:11

Cat Plus Plus