Search code examples
pythonpython-3.xpython-2.7inheritancesuper

back compatible call to super() for python2/3


I have some code with I need to run in Python 2 and 3. I have a class

class myClass:
  def __init__(self):

with a child. I have tried:

  from myClassfile import myClass as myBaseClass
  class myClass(myBaseClass):
          def __init__(self):
              super().__init__()

But it failed due known python2/3 differences. I have followed TypeError: super() takes at least 1 argument (0 given) error is specific to any python version?

until:

from myClassfile import myClass as myBaseClass
class myClass(myBaseClass):

  def __init__(self):
      super(myClass,self).__init__()

but this still fails due to:

TypeError: super() argument 1 must be type, not classobj

Solution

  • In Python 2, a class must inherit from object in order to be a new-style-class:

    class myClass(object):
        def __init__(self):
    

    In Python 3, that may or may not be done - it does not make a difference.

    Since in your code myClass inherits from myBaseClass, you should make sure that myBaseClass inherits from object:

    class myBaseClass(object):
        ...
    
    class myClass(myBaseClass):
        def __init__(self):
            super(myClass, self).__init__()