2

I am writing a program that will at some point procedurally generate a new version of itself, save it to a file, and then import it from that file, overwriting relevant classes by the imported ones. And by saying that I mean the whole class will be redefined, not just specific methods changed.

So my question is, what happens to the already created instances of this class while it is redefined? Suppose you have:

class FooType():
  def __init__(self):
    pass

  def doSomething(self):
    print("Hello from old FooType")

foo = FooType()

# some code is executed here

class FooType():
  def __init__(self, bar=None):
    self.bar = bar if bar is not None else 'lorem ipsum'

  def doSomething(self):
    print("Hello world")

  def somethingNew(self):
    print("Hey, I can do this now!")

foo.doSomething()

which gives:

Hello from old FooType

meaning the foo object has not been updated, but why?

DarklingArcher
  • 227
  • 1
  • 7
  • 1
    Because you've just shadowed the old class definition, you haven't actually changed the `foo` instance at all. – jonrsharpe Dec 17 '19 at 12:50

1 Answers1

3

Because you are simply re-binding the name FooType to another object (which is also a class). The old class object lives on in memory, as it can still be referenced via the instance foo: id(foo.__class__). Python's "variables" are just names for objects that live somewhere in memory. When an object can't be referenced by any name, it gets garbage-collected.

It might be possible to re-assign the instance's type at runtime by modifying the __class__ attribute, but this is definitely not standard practice:

One option is using the adapter pattern, even though I'm not sure it's applicable to your use case: Change type of an object after its creation (typecasting in Python)

sammy
  • 857
  • 5
  • 13
  • 2
    Does this mean that if I set `foo.__class__` to point to the new `FooType`, my object would behave like an instance of it? – DarklingArcher Dec 17 '19 at 15:04
  • That's an interesting question, I updated my answer according to what I found on this topic. – sammy Dec 17 '19 at 15:40