__super__ and super()

Example code:

class Foo:
    def __init__(self):
        self.bar = 1
    def __super__(self):
        return super()
    class SubFoo:
        def __init__(self):
            self.bar = 2
        def __super__(self):
            return super()
        
def super(obj):
    return obj.__super__()

basically, it will return the class’ parent or a generic object type if there is no parent class

It’s not clear to me what you’re suggesting. Can you give some more detail? Are you aware of the existing super function? Are you proposing a change to its behavior?

  1. There is always at least one superclass, except for object itself.
  2. Python supports multiple inheritance, so the concept of “the” parent is wrong. Classes (apart from object) always have one or more parent classes.
  3. Why don’t you look in the MRO instead?
  4. Or the __base__ and __bases__ attributes?
>>> class A: pass
... 
>>> class B: pass
... 
>>> class C(A, B): pass
... 
>>> C.__base__
<class '__main__.A'>
>>> C.__bases__
(<class '__main__.A'>, <class '__main__.B'>)
>>> C.mro()
[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, 
<class 'object'>]

If you are manually calling “the parent” in your methods, you are probably doing it wrong, and your class will needlessly(?) be unusable in multiple inheritance.

SubFoo is not a subclass of Foo. It is an independent class that inherits directly from object, not from Foo. The only thing which is special about SubFoo is that it is accessible from Foo as an attribute.

I’m not entirely sure what you’re trying to do here, but it’s possible you’re trying to get access to the zero-arg form of super() from outside the class? If so, you can use this definition: super() is equivalent to super(__class__, self), where __class__ refers to the currently-being-defined class, and self is the object in question. So if you want to know the superclass from Foo, it’s super(Foo, obj), and if you want to know the superclass from SubFoo, that’s super(SubFoo, obj). Either way, what you get back is not a class, though, it’s a magic thing that lets you call methods by skipping the MRO up to and including the class in question, so it’ll start from the next class after that when looking for methods.

But if that isn’t what you’re after, describe what you’re trying to do.

Is this another Ideas post that should have been a Help post?