Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if you save a call to super in a variable for future use?

Tags:

python

super

Forgive me if I'm being ignorant of the obvious here, but what would happen if you save a call to super in a variable and use it later.

Here is a part of a class definition to show you what I mean.

class CaselessDict(dict):

    def __init__(self, *args, **kwargs):
        self.super = super(CaselessDict, self) # save super
        self.update(*args, **kwargs)

    def __getitem__(self, key):
        key = self.parsekey(key)
        return self.super.__getitem__(key) # use saved super

This came up when I was implementing this CaselessDict class and almost every method had super in it.

like image 446
qtwtetrt Avatar asked Oct 10 '22 19:10

qtwtetrt


1 Answers

The expected thing happens: self.super will just hold a super object that acts just like super(CaselessDict, self).

The problem with this approach is that each instance only has one super attribute, so if you had more classes that would use this technique, only the one that assigned to super last would function properly. Ouch! So, it's generally not a good idea to do this. You could name the attribute __super so it gets mangled, but I recommend just calling super(CaselessDict, self), as everybody else does.

Of course, the grass is greener in Python 3, where a plain super() call is enough.

like image 147
Petr Viktorin Avatar answered Oct 12 '22 09:10

Petr Viktorin