Search code examples
pythonreferenceinitializationpython-3.9python-class

Create new instance only if not exist else return existing without new initialization


I want to store instances from class in itself. And if the __new__ method is calling this should return the the instance if exists, but withou new initialization.

I wrote a minimal example:

from pprint import pprint


class A:
    _l = {}

    def __init__(self, name : str, initalize: bool = True, **kwargs) -> None:
        print("In init")
        if kwargs.get('initalize'):
            print("no initialization")
            print(self.numbers)
            self.name = self.name
            self.numbers = self.numbers
            return
        self.name = name
        self.numbers = []

    def __new__(cls, name:str, *args, **kwargs):
        a = A._l.get(name)

        if a:
            print("Use existing A")
            kwargs['initalize'] = False
            return a
        
        print(f"Create new A object with name: {name}")
        cls._l[name] = super(A, cls).__new__(cls)
        return cls._l[name]



l = [
        A('Alex'), A('Gerrit'), A('Jannis'), A('Hannes'),
        A('Hannes'), A('Alex'), A('Mumpitz')
    ]

print("\n#### 1 ####")
c = 0
for a in l:
    a.numbers.append(1)
    a.numbers.append(2)
    print(f"[{c}] {a} : {a.numbers}")
    c += 1

print("\n#### 2 ####")
for n in ['Alex', 'Mumpitz']:
    current = A(n)
    pprint(f"current: {current}")
    current.numbers.append(3)

print("\n#### 3 ####")
for a in l:
    print(a.numbers)

The output looks like this:

Create new A object with name: Alex
In init
Create new A object with name: Gerrit
In init
Create new A object with name: Jannis
In init
Create new A object with name: Hannes
In init
Use existing A
In init
Use existing A
In init
Create new A object with name: Mumpitz
In init

#### 1 ####
[0] <__main__.A object at 0x7f7b2af87d30> : [1, 2]
[1] <__main__.A object at 0x7f7b2af87cd0> : [1, 2]
[2] <__main__.A object at 0x7f7b2af87be0> : [1, 2]
[3] <__main__.A object at 0x7f7b2af874c0> : [1, 2]
[4] <__main__.A object at 0x7f7b2af874c0> : [1, 2, 1, 2]
[5] <__main__.A object at 0x7f7b2af87d30> : [1, 2, 1, 2]
[6] <__main__.A object at 0x7f7b2af87460> : [1, 2]

#### 2 ####
Use existing A
In init
'current: <__main__.A object at 0x7f7b2af87d30>'
Use existing A
In init
'current: <__main__.A object at 0x7f7b2af87460>'

#### 3 ####
[3]
[1, 2]
[1, 2]
[1, 2, 1, 2]
[1, 2, 1, 2]
[3]
[3]

What i want? The third output should look like the following code, but without create a external class or holder.

#### 3 ####
[1, 2, 3] 
[1, 2]
[1, 2]
[1, 2, 1, 2]
[1, 2, 1, 2]
[1, 2, 3]
[1, 2, 3]

Solution

  • First I tried to finish your code with minimal changes. Instead of the not working initialize flag, I added hasattr as a test if the initialization took place or not:

    class A:
        _l = {}
    
        def __init__(self, name : str, **kwargs) -> None:
            print("In init")
            if hasattr(self, 'name'):
                print("no initialization")
                return
            self.name = name
            self.numbers = []
    
        def __new__(cls, name:str, *args, **kwargs):
            a = A._l.get(name)
            if a:
                print("Use existing A")
                return a
        
            print(f"Create new A object with name: {name}")
            cls._l[name] = super(A, cls).__new__(cls)
            return cls._l[name]
    

    And I'm adding an alternative with a factory function that I find simpler:

    class _A: 
        def __init__(self, name : str) -> None:
            print(f"In init A({name})")
            self.name = name
            self.numbers = []
    
    def A(name, _instances={}):  # deliberate use of a mutable default arg
        if name not in _instances:
            _instances[name] = _A(name)
        return _instances[name]
    

    First I was considering another alternative with a dict subclass having a __missing__ function added, but all A(name) had to be replaced by A[name], so I dropped the idea.


    However, the output is not exactly as expected:

    #### 3 ####
    [1, 2, 1, 2, 3]
    [1, 2]
    [1, 2]
    [1, 2, 1, 2]
    [1, 2, 1, 2]
    [1, 2, 1, 2, 3]
    [1, 2, 3]
    

    but I hope it is correct.