Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The __new__ method is a special, implicitly static method responsible for creating and returning a new instance of a class. It represents the allocation phase of the object instantiation lifecycle, executing strictly before the __init__ method, which handles the initialization phase. When a class is called to instantiate an object, Python internally invokes __new__ to construct the instance in memory. Only if __new__ successfully returns an instance of the requested class does Python proceed to call __init__ to populate its initial state.

Syntax and Signature

class Constructable:
    def __new__(cls, *args, **kwargs):
        # Memory allocation and object creation
        instance = super().__new__(cls)
        return instance
  • cls: The first parameter is the class itself that is being instantiated. Unlike instance methods that receive self, __new__ receives the class reference.
  • *args, **kwargs: Any positional or keyword arguments passed to the class constructor are forwarded to __new__.
  • return: The method must explicitly return a valid object reference.

Internal Mechanics

  1. Invocation: When you execute obj = MyClass(x, y), Python translates this into instance = MyClass.__new__(MyClass, x, y).
  2. Delegation: To actually allocate memory, __new__ typically delegates to the base object class using super().__new__(cls).
  3. Initialization Trigger: Python inspects the return value of __new__.
    • If the returned object is an instance of cls (or a subclass), Python automatically invokes __init__(instance, x, y).
    • If __new__ returns an object of a completely different class, or returns None, the __init__ method of cls is bypassed entirely.

Execution Lifecycle Demonstration

The following code illustrates the exact sequence of operations during instantiation:
class Lifecycle:
    def __new__(cls, *args, **kwargs):
        print(f"1. __new__ invoked for {cls.__name__}")
        
        # Delegate to object.__new__ to allocate memory
        instance = super().__new__(cls)
        
        print(f"2. Memory allocated. Instance ID: {id(instance)}")
        return instance

    def __init__(self, value):
        print(f"3. __init__ invoked. Initializing Instance ID: {id(self)}")
        self.value = value


# Triggering the lifecycle
obj = Lifecycle(42)

Technical Constraints and Behaviors

  • Implicitly Static: You do not need to decorate __new__ with @staticmethod. The Python interpreter automatically binds it as a static method at the C-API level.
  • object.__new__ Signature: While your custom __new__ method accepts *args and **kwargs, the base object.__new__ method strictly accepts only the cls argument. Passing initialization arguments to super().__new__(cls, *args, **kwargs) will raise a TypeError in modern Python.
  • Immutability: Because __new__ handles the actual creation of the object before it exists in memory, it is the only mechanism available to intercept and alter the instantiation process of built-in immutable types (such as tuple, int, or str).
Master Python with Deep Grasping Methodology!Learn More