__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): pass
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.
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 : s1 = Singleton() In : s2 = Singleton() In : s1 is s2 Out: 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 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 peep 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:
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 found files in the editor, find the lines of interest to you and study the use cases from the creators of Python…