Search code examples
python-3.xclassmonkeypatching

Update class instance in Python console


I'm building some code, so it's convenient to have it live in the Python console for easy experimentation. 'cept that classes have state and I'm not sure what the best way is to update an existing instance of a class such that I can continue toying with it.

Say, for instance, I have this class:

class Cheese:
  def __init__(self):
    self.brand    = 'Kraft'
    self.quantity = 4

And I create an instance:

c = Cheese()

Now, I modify the class like so:

class Cheese:
  def __init__(self):
    self.brand    = 'Kraft'
    self.quantity = 4
  def munch():
    self.quantity = self.quantity-1
  #Possibly many other new methods or changes to existing methods
  #Possibly incrementally updating things many times

How can I update c such that it becomes an instance of the updated class while retaining its previous internal state? At the moment, I have to re-run a lot of somewhat expensive code.


Solution

  • I am assuming that you are using 3.x, rather than 2.x and 'classic classes'. If so, I believe updating c.__class__ does what you want.

    >>> class C():
        pass
    
    >>> c = C()
    >>> class C():
        def __init__(self): self.a = 3
    
    >>> c.__class__
    <class '__main__.C'>  # but actual reference is to old version
    >>> id(C)
    2539449946696
    >>> id(c.__class__)
    2539449972184
    >>> c.__class__ = C
    >>> id(c.__class__)
    2539449946696