Welcome, guest | Sign In | My Account | Store | Cart

Take an instance (call it foo) and create a factory class (call it InstanceFactory) that produces foo's. Then inherit from InstanceFactory.

Python, 6 lines
1
2
3
4
5
6
def MakeClassFromInstance(instance):
    from copy import deepcopy
    copy = deepcopy(instance.__dict__)
    InstanceFactory = type('InstanceFactory', (instance.__class__, ), {})
    InstanceFactory.__init__ = lambda self, *args, **kwargs: self.__dict__.update(copy)
    return InstanceFactory

2 comments

Gabriel Genellina 14 years, 1 month ago  # | flag

Perhaps one should warn the users:

  • this only works with new-style classes

  • the original per-instance state becomes shared among all instances:

>>> class Foo(object):
...   def __init__(self):
...     self.items = []
...
>>> x = Foo()
>>> y = Foo()
>>> x.items.append(1)
>>> y.items
[]
>>> Foo2 = MakeClassFromInstance(x)
>>> z = Foo2()
>>> x.items.append(5)
>>> x.items
[1, 5]
>>> z.items
[1, 5]
Daniel Cohn (author) 14 years, 1 month ago  # | flag

Gabriel, thank you for that comment! While this recipe only applies to new style classes, the original per-instance state is No Longer shared among all instances. Below is a reproduction of your example using the updated recipe. Thanks again, and more discussion + use cases to follow.

>>> class Foo(object):
...     def __init__(self):
...         self.items = []
... 
>>> x = Foo()
>>> y = Foo()
>>> x.items.append(1)
>>> Foo2 = MakeClassFromInstance(x)
>>> z = Foo2()
>>> x.items.append(5)
>>> x.items
[1, 5]
>>> z.items
[1]
>>>
Created by Daniel Cohn on Tue, 2 Feb 2010 (MIT)
Python recipes (4591)
Daniel Cohn's recipes (6)

Required Modules

  • (none specified)

Other Information and Tasks