title: Upcast instance to parent class in python
body: <p>(How) Is it possible in Python to treat an instance of class <code>B</code> exactly as an instance of class <code>A</code>, where <code>A</code> is a parent of <code>B</code> (like up-casting in compiled languages)?</p>
  <p>Say we have the following:</p>
  <pre><code>class A:
      def __init__(self, prop=None):
          self.prop = prop
  
      def f(self):
          return 'A.f'
  
      def g(self):
          return 'A.g', self.f()
  
  
  class B(A):
      def f(self):
          return 'B.f'
  
      def g(self):
          return 'B.g', self.f()
  </code></pre>
  <p>Calling <code>A().g()</code> produces <code>('A.g', 'A.f')</code>, whereas <code>B().g()</code> produces <code>('B.g', 'B.f')</code>. Calling <code>super(B, B()).g()</code> produces <code>('A.g', 'B.f')</code>, which is different from compiled languages, so I cannot use <code>super</code>. Instead, I need a function that changes the type from which an instance's methods are resolved, but preserves (a reference to) the original state. In short, I'm looking for a way to do this:</p>
  <pre><code>b = B(object())
  a = upcast(b, A)
  a.prop = object()
  
  assert isinstance(a, A)
  assert a.g() == ('A.g', 'A.f')
  assert a.prop is b.prop
  </code></pre>
  <p>The closest I could get is</p>
  <pre><code>a = copy.copy(b)
  a.__class__ = A
  a.__dict__ = b.__dict__
  </code></pre>
  <p>(assuming <code>A/B</code> are &quot;nice&quot; &quot;heap&quot; classes), but this makes unnecessary copies of all objects in the <code>__dict__</code> before I discard them. Is there a better way to do this?</p>