Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

In Python 3 one can use super() instead of super(MyClass, self), but this only works in methods that were defined inside the class. As described in Michele Simionato's article the following example does not work:

def __init__(self):
    print('calling __init__')
    super().__init__()

class C(object):
    __init__ = __init__

if __name__ == '__main__':
    c = C()

It fails because super() looks for a __class__ cell, which is not defined in this case.

Is it possible to set this cell manually after the function has been defined, or is that impossible?

Unfortunately I don't understand how cells work in this context (didn't find much documentation for that). I'm hoping for something like

__init__.__class_cell_thingy__ = C

Of course I would only use this in a situation where the class assignment is unambiguous/unique (the whole process of adding methods to a class in is automatized in my case, so it would be simple to add such a line).

share|improve this question
3  
"Is it possible to set this cell manually"? When you tried this, what happened? – S.Lott Feb 3 '11 at 10:57
    
But how can I get access to this cell after defining the function? __init__.__class__ is of course something else. I have now edited the question to clarify this. – nikow Feb 3 '11 at 10:59
    
Why do you want to define the function outside of the class? You'd want this if you want to reuse a function, or use a function as a method multiple times. You can't do those things and use super(...) correctly. And if you're modifying a class at runtime, you can simply hardcode it. – Rosh Oxymoron Feb 3 '11 at 11:06
    
@Rush: Obviously the use cases for this are somewhat complicated. In my case it's related to aspect oriented programming. The function is only added to one class, so I could hardcode it (but that isn't my question). If you think that what I ask is impossible then please explain why, and I'll be happy accept your answer. – nikow Feb 3 '11 at 11:13
1  
@nikow: Well, it seems a better idea to call super() inside the class's own __init__, and then maybe wrap that init with a decorator instead. – Lennart Regebro Feb 3 '11 at 11:36
up vote 10 down vote accepted

Seriously: you really don't want to do this.

But, it's useful for advanced users of Python to understand this, so I'll explain it.

Cells and freevars are the values assigned when a closure is created. For example,

def f():
    a = 1
    def func():
        print(a)
    return func

f returns a closure based on func, storing a reference to a. That reference is stored in a cell (actually in a freevar, but which one is up to the implementation). You can examine this:

myfunc = f()
# ('a',)
print(myfunc.__code__.co_freevars)
# (<cell at 0xb7abce84: int object at 0x82b1de0>,)
print(myfunc.__closure__)

("cells" and "freevars" are very similar. Freevars have names, where cells have indexes. They're both stored in func.__closure__, with cells coming first. We only care about freevars here, since that's what __class__ is.)

Once you understand that, you can see how super() actually works. Any function that contains a call to super is actually a closure, with a freevar named __class__ (which is also added if you refer to __class__ yourself):

class foo:
    def bar(self):
        print(__class__)

(Warning: this is where things get evil.)

These cells are visible in func.__closure__, but it's read-only; you can't change it. The only way to change it is to create a new function, which is done with the types.FunctionType constructor. However, your __init__ function doesn't have a __class__ freevar at all--so we need to add one. That means we have to create a new code object as well.

The below code does this. I added a base class B for demonstrative purposes. This code makes some assumptions, eg. that __init__ doesn't already have a free variable named __class__.

There's another hack here: there doesn't seem to be a constructor for the cell type. To work around that, a dummy function C.dummy is created which has the cell variable we need.

import types

class B(object):
    def __init__(self):
        print("base")

class C(B):
    def dummy(self): __class__

def __init__(self):
    print('calling __init__')
    super().__init__()

def MakeCodeObjectWithClass(c):
    """
    Return a copy of the code object c, with __class__ added to the end
    of co_freevars.
    """
    return types.CodeType(c.co_argcount, c.co_kwonlyargcount, c.co_nlocals,
            c.co_stacksize, c.co_flags, c.co_code, c.co_consts, c.co_names,
            c.co_varnames, c.co_filename, c.co_name, c.co_firstlineno,
            c.co_lnotab, c.co_freevars + ('__class__',), c.co_cellvars)

new_code = MakeCodeObjectWithClass(__init__.__code__)
old_closure = __init__.__closure__ or ()
C.__init__ = types.FunctionType(new_code, globals(), __init__.__name__,
    __init__.__defaults__, old_closure + (C.dummy.__closure__[0],))

if __name__ == '__main__':
    c = C()
share|improve this answer
    
Thanks, excellent answer. It's nice to know how these things work. I think I'll take your advise and stick to the explicit super calls for now. Until Python 3 becomes predominant this is somewhat academic anyway. – nikow Feb 3 '11 at 12:20
    
P.S. Seems that this answer pushed pushed you to 10k rep :-) – nikow Feb 3 '11 at 12:23
1  
Another trick is to define a function inside a another function with a single argument __class__ and then return the inner function (or just its closure). Then you wouldn't need the dummy method there to create the closure, or you might as well define the actual method as such inner function. Another thing is that you might use a class container (probably with an auxiliary metaclass with methods hiding the magic) to store the functions, then you wouldn't have to create custom code objects with that scary call. – Rosh Oxymoron Feb 3 '11 at 14:25

You can use the function's dictionary.

def f(self):
    super(f.owner_cls, self).f()
    print("B")

def add_to_class(cls, member, name=None):
    if hasattr(member, 'owner_cls'):
        raise ValueError("%r already added to class %r" % (member, member.owner_cls))
    member.owner_cls = cls
    if name is None:
        name = member.__name__
    setattr(cls, name, member)

class A:
     def f(self):
         print("A")

class B(A):
     pass

add_to_class(B, f)

B().f()

You can even add another attribute member_name if you don't want to hardcode the name of the name of the member inside the function.

share|improve this answer
    
That would work, but I'm not sure if I would prefer it to the explicit solution with writing class. After all I know which class the method will belong to, I just want to benefit from the more convenient Python 3 super(). – nikow Feb 3 '11 at 12:03
2  
If you're doing something like this in the first place, you probably want to be able to assign the function to more than one class. – Glenn Maynard Feb 3 '11 at 12:57
    
@Glenn: Yes, you are right. While this isn't my primary use case I remembered that there are cases where this would be an issue. – nikow Feb 3 '11 at 13:20

Maybe, but by would you? In both cases you need to somehow be explicit of which class it is, because the implicit way didn't work. Maybe you can set the cell explicitly somehow, but there is no reason to do that. Just pass in the parameters explicitly.

def __init__(self):
    print('calling __init__')
    super(self.__class__, self).__init__()

class C(object):
    __init__ = __init__

if __name__ == '__main__':
    c = C()

(It's better if you can pass in the actual class directly, like so:

def __init__(self):
    print('calling __init__')
    super(C, self).__init__()

class C(object):
    __init__ = __init__

if __name__ == '__main__':
    c = C()

But if you can that, you could put the __init__ on C directly, so assume you can't.

share|improve this answer
2  
Thanks for answering, but what you suggest here is very wrong. You can't use self.__class__ with super, as was recently exaplained here: stackoverflow.com/questions/4883822/… – nikow Feb 3 '11 at 11:19
    
@nikow: Well, if you are going to subclass it you can get into problems, yes, if that subclass also uses super(). So you want to use the same __init__ for many different classes (because otherwise you wouldn't have defined it outside of the class) and you don't know which clases, and you don't know if or how these classes are subclassed? In that case I would say you are solving the problem wrong. Can I suggest a class decorator, or a component architecture with adapters? – Lennart Regebro Feb 3 '11 at 11:21
    
@Lennart: The added function is defined elsewhere following ideas from AOP, and this has worked pretty well in our project. In the real code these "aspects" are activated/deactivated at runtime, so using decorator classes is not really an option. I was just hoping that one could enable the simplified super() calls, after all they were added to Python 3 for a reason. – nikow Feb 3 '11 at 11:43
    
@nikow: Sure, I understand. It's just that calling super() from the added methods in your case seems to be a bad idea. Hence the suggestion of using adapters (that fulfill the same function of making code being defined somewhere else) or decorators. Since it's runtime, deocrators are out of the questions, but adapters isn't. You should really look at the Zope component Architecture, which is aspect oriented, even if it doesn't like to brag about it. :) But it's probably too late for an ongoing project, but you might get ideas. – Lennart Regebro Feb 3 '11 at 11:53
    
P.S. The downvote wasn't me. – nikow Feb 3 '11 at 11:53

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.