python – Why is __new__ necessary and what is its practical use?


Why __new__ needed in Python development and when to use it?

There's a nice comment in 2 words on what the __new__ magic method is: a static method, called when an instance of the class is created . In general, first he, then __init__ , I think I understood correctly.

I am ashamed to admit, but I have never seen the application of this magical method in practice, even on a simple toy example it looks redundant.

class Foo(object):
    def __new__(cls, *args, **kwargs):
        print "Creating Instance"
        instance = super(Foo, cls).__new__(cls, *args, **kwargs)
        return instance

    def __init__(self, a, b):
        self.a = a
        self.b = b

    def bar(self):

Can someone give a simple example where there is a valid use __new__ and explain why it is needed and when it should be used?


From the official documentation :

__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.

Here are examples of the actual use of the __new__() method :


class Singleton(object):
    _instance = None  # Keep instance reference 

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = object.__new__(cls, *args, **kwargs)
        return cls._instance


In [26]: s1 = Singleton()

In [27]: s2 = Singleton()

In [28]: s1 is s2
Out[28]: True

An example of usage in the pathlib module (from the standard library in Python 3.x):

class PurePath(object):

    def __new__(cls, *args):
        """Construct a PurePath from one or several strings and or existing
        PurePath objects.  The strings and path objects are combined so as
        to yield a canonicalized path, which is incorporated into the
        new PurePath object.
        if cls is PurePath:
            cls = PureWindowsPath if == 'nt' else PurePosixPath
        return cls._from_parts(args)

NOTE: if you are interested in examples of real and correct use of methods / functions in Python, then it is better to peep how the authors of the Python standard library use them:

  • go to the <Python_installation>/Lib directory and look in which files the method you are interested in is present: def __new__ :

     C:\Users\Max\Anaconda3\Lib>grep -l "def __new__(" *.py
  • open the found files in the editor, find the lines of interest to you and study the use cases from the creators of Python…

Scroll to Top