1

Is it possible in python to recreate an object from already instatiated object, with all it's arguments passed into __init__ method?

Something similar to inspect.getcallargs, but for class instances.

For example:

class A:
    def __init__(self, some_arg):
        self.some_arg = some_arg

def f(a):
    # somehow get all arguments from `a`, with which it was created
    # kwargs = ...?
    # and create a new instance of class with the same (or modified) args:
    return a.__class__(**kwargs)

a = A(100)
new_a = f(a)
print(new_a.some_arg)
>>> 100
qr0sity
  • 13
  • 3
  • See [Main purpose of `__repr__` in python](http://stackoverflow.com/questions/15661063/main-purpose-of-repr-in-python) – Peter Wood May 03 '17 at 00:07

1 Answers1

2

No, it is not possible, because the arguments of the __init__ method might have been discarded, used to compute other values, or saved in a multitude of different manners which would be impossible to create a generic method to retrieve.

However, you can achieve flexible object initialization from preset configurable parameters by using the Factory pattern, and you can copy existing objects using copy.deepcopy. (However, be aware that there are edge cases to deepcopy, so be careful when using it and be sure to read the docs)

Pedro Castilho
  • 10,174
  • 2
  • 28
  • 39