Home python Why is __new__ and what is its practical use?

Why is __new__ and what is its practical use?

Author

Date

Category

Why is __new__needed in Python development and when to use it?

There is a good comment in 2 words on what the magic method is __new__: static method, called when the class is instantiated . In general, first he, then __init__, I think I understood correctly.

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

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):
        pass

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


Answer 1, authority 100%

From 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 how the method is actually used __new__():

Singleton

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

check:

In [26]: s1 = Singleton()
In [27]: s2 = Singleton()
In [28]: s1 is s2
Out[28]: True

An example of use in the module pathlib ( 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 os.name == '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 spy on how the authors of the Python standard library use them:

  • go to the <Python_installation>/Libdirectory 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
    _py_abc.py
    _pydecimal.py
    _pyio.py
    _threading_local.py
    abc.py
    codecs.py
    datetime.py
    enum.py
    fractions.py
    functools.py
    pathlib.py
    pstats.py
    sre_constants.py
    ssl.py
    turtle.py
    typing.py
    weakref.py
    
  • open the files you find in the editor, find the lines you are interested in, and study the use cases from the creators of Python …

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions