__new__() in python

Lately I started looking into Django code and wish to write about internals of Django. I started with Django models and will be writing about it soon.
For understanding how Django models work, I had to understand what metaclasses are and how metaclasses work. Metaclasses use method “__new__” and so I looked at what “__new__” does.

###As __new__ is a static method, we will see a lttle bit about static methods and then __new__ in detail.

Understanding static methods.

Understanding method “__new__” of any class. We will see how to override method __new__ in a class.

Also, I will be trying all the code we write here on Ipython and I suggest you to try everything on Ipython as well.

In this case, met() is an instance method. So, it is expected that we pass an instance of A as the first argument to met.

Let’s create an object and call met() on the created object and pass two arguments to met().

In [4]: obj = A()
In [5]: obj.met(1,2)
1 2 #output

####What happened here?
When we called met(), we passed two arguments although met() expects three argument as per its definition. When we wrote obj.met(1, 2), interpreter took care of sending instance obj as the first argument to met() and 1 and 2 were passed as second and third arguments respectively.

Let’s try calling met() without an instance or in other words let’s call the method using class.

We defined met() as an instance method of class A, so it expected an instance of A as the first argument. As its very clear from the error, met() expected an instance of A as the first argument but got an ‘int’ instead.

If we pass an instance of A as the first argument, it will work as expected.

In [7]: A.met(obj, 3, 4)
3 4 #output

Notice that we called the method on class A and not on an instance of A. But we took care of sending an instance of A as the first argument to met() and it worked as expected.

####What does @staticmethod above the method definition do?
Its a decorator which changes a method to static method. It means the method is no longer an instance method, which means that the method does not expect its first argument to be an instance. So, for our method definition, the method does not expect its first argument to be an instance of B.
Even if we call the method on an instance of B, current instance will not be passed as the first argument to this method, since its a static method. For instance method that we saw earlier the current instance was passed as the first argument.

In [9]: B.met(5,6)
5 6 #output

Here we were able to call the method on the class and were not required to pass an instance of B as the first argument.

Let’s call this method on an instance.

In [10]: b = B()
In [11]: b.met(5,6)
5 6

Here we called the method on an instance and passed two arguments. Since its a static method, the current instance i.e b was not passed as the first argument to met().
Had it not been a static method, current instance would have been passed as first argument, 5 as second argument and 6 as third argument.

###Understanding method __new__ of a class. We will also see how to override method __new__ in a class.
First let’s see a little bit about __init__

In __init__, we print something as we enter the method which is to validate that __init__ has been called. Then we print the first argument which is self and then we perform some assignments. __init__ is an instance method and expects the first argument to be an instance.

Let’s call the class passing it two arguments. Keep in mind the part call the class, we are going to again use it in next few lines. If you have any confusion about the part calling the class, it will be clear in next few lines.

In [16]: a = A(1,2)
init gets called #output
self is <__main__.A object at 0x3357210> #output

Notice the second line of output which is “self is <__main__.A object at 0x3357210>”. As apparent from second line of output, when __init__ is entered, object/instance has already been created by that time. Its only the assignment which is done in __init__, althought you could do some other stuff as well. But __init__ doesn’t create the instance. __init__ receives the created instance as the first argument.

####What creates the object?
Method __new__() creates the object.

####What is __new__?

__new__ is a static method which creates an instance. We will see the method signature soon. One reason i could think of having __new__ as a static method is because the instance has not been created yet when __new__ is called. So, they could not have had it as an instance method.

__new__ gets called when you call the class. Call the class means issuing the statement “a=A(1,2)”. Here A(1,2) is like calling the class. A is a class and we put two parenthesis in front of it and put some arguments between the parenthesis. So, its like “calling the class” similar to calling a method.

__new__ must return the created object.

Only when __new__ returns the created instance then __init__ gets called. If __new__ does not return an instance then __init__ would not be called. Remember __new__ is always called before __init__.

__new__ gets passed all the arguments that we pass while calling the class. Also, it gets passed one extra argument that we will see soon.

####How was the instance created in the last example when we didn’t define __new__?
class A extends from object(Here we mean the class named object) i.e subclasses from object. object defines a method __new__, so A gets this method from object since its extending object. This inherited __new__ created the instance of A.

####Method signature of __new__
__new__ receives the class whose instance need to be created as the first argument. This statement could be a little confusing, just continue reading and see the next example and again read it after seeing the example, it will be clear. The other arguments received by __new__ are same as what were passed while calling the class.

So, __new__ receives all the arguments that we pass while calling the class. Also, it receives one extra argument. This extra argument is the class whose instance need to be created and it will be received as first argument by __new__.

Here we override __new__ that we inherit from the superclass. We are printing all the arguments that this method receives so that we can check what gets passed to __new__.
Let’s try to create an instance of A by calling the class.

As we mentioned earlier, __new__ gets called when we call the class. As is apparent from the output __new__ was called and it printed three lines of output.

First line of output prints the first argument received by __new__. As we can see, it is class A itself. We tried to create an instance of A and __new__ of A received class A itself as the first argument.
This is what we meant when we said “__new__ receives the class whose instance need to be created as the first argument”. Now go back to the section “Method signature of __new__” and read it again.

While calling the class we did not pass any arguments. So our output shows that args and kwargs did not receive anything.

You can verify that all the arguments passed while calling the class gets sent to __new__. Just call the class passing it some arguments.

We tried to create an instance and then tried printing the instance. But an instance of A was not created as apparent from the last print statement which printed None.

####Why did this happen?
As we know if we don’t return any value from a method, it implicitly returns None.
Under the section “What is __new__”, we mentioned that __new__ must return the created instance.
Here we did not return the created instance from __new__, so None was implicitly returned and was assigned to a.

As we mentioned earlier when a class gets called, first __new__ is called. Only when __new__ returns an instance then __init__ is called.

In our previous example __new__ did not return an instance. So __init__ was not called. Had __init__ been called we would have seen the print statements that we have inside __init__.

Also since __new__ did not return an instance, a will still be None. Verify that.

In [32]: print a
None #output

Let’s redefine the class to make it proper. We should return an instance from __new__, so that __init__ gets called and we get the desired behaviour.

In case we don’t override __new__, __new__ of parent class creates the instance and then __init__ gets called. In case we are overriding __new__, we should call the __new__ of parent class to get the created instance. However if you know how object creation works at the low level and you can implement it in your overridden __new__, you don’t need to call parent __new__ to get the created instance. I don’t know such details of how object creation work and will use the parent __new__ to get the created instance.

Once we get the created instance we can perform any extra operations we wish before returning the instance from __new__ method.

For demonstration purpose, let us take a weird example where we need to add an attribute named ‘created_at’ to the created instance. For our case lets consider it needs to be done inside the __new__ method, althought we could have done it inside __init__.

In the first line of __new__, we called the __new__ of parent class to get the created instance. __new__ of parent class should be passed the same arguments that we received in the overridden __new__. __new__ of parent class i.e __new__ of class object knows how to create an instance and it returns the created instance.

In the next line, we used inbuilt method setattr() to set an attribute ‘created_at’ on the newly created instance. The value we set for this attribute is the current time. This line is equivalent to writing new_instance.created_at=datetime.datetime.now().

In the final line we returned the newly created instance. Since we are returning an instance from __new__, __init__ will be called passing it whatever arguments were used in the class call. Let’s verify this.

In [36]: obj1 = A(1,2)
inside init #output

This statement suggests that __init__ was called. Let’s print the created instance.

In [37]: obj1
Out[37]: <__main__.A at 0x3357390>

Notice that earlier when we were not returning anything from __new__ and were trying to print it, we were getting output as None. But this time the output shows that obj1 refers to an instance of A.

We can verify that obj1 has an attribute ‘created_at’ and __init__ was properly executed by printing the three attributes of obj1.

Pay attention to first line of A’s new. Instead of passing cls as the first argument to object.__new__, we pass class B as first argument.
Let’s see what happens in such case.

In [62]: a = A()
In [63]: print a
<__main__.B object at 0x7f912c036750> #Output. Tried creating an instance of A but got an instance of B

We tried to create an instance of A. But when we printed it, we realise that an instance of B has been created.

This happened because we passed class B as the first argument to object.__new__. This shows that whatever class we pass to superclass’ __new__, an instance of that class will be created.

Remember __new__ receives the class whose instance need to be created as first argument. So for any __new__, the first argument (which is cls for our case) will always refer to the class inside which __new__ is defined. So, for our case, cls will be class A.

Here we wanted to create an instance of A. So, class A must be passed as first argument to object.__new__. Inside __new__ of class A, cls refers to class A. So, we need to pass cls as first argument to object.__new__.

That’s why if we want proper behaviour we need to pass the same arguments to the superclass’ __new__ as it was received by the overridden __new__.

We can make that single line change in A’s __new__ and our code will behave as expected.