Esteemed Python Gurus,

I think, I actually know the answer to this question, but - maybe beyond reason - I'm hoping there to be some magic. Consider the following code:

    from types import MethodType

    class A(object):
        pass
        def m(self, x):
            print(f"A.m({x})")
    class B(A):
        def m(self, x):
            print(f"B.m({x})")
            ss = super()
            ss.m(x)

    def method(self, s):
        print(f"method({s})")
        try:
            ss = super() # <-- Complains about __class__ cell not being found
        except:
            print("I shouldn't need to do this!")
            ss = super(type(self), self) # <-- Works just fine
        ss.m(s)

    a = B()
    a.m(41)
    a.m = MethodType(method, a)
    a.m(42)


In the function 'method', I try to access the super() class. Now, of course that makes no sense as a stand-alone function, but it does, once it gets injected as a method into 'a' below.

The two-parameter version of the call of course works without a hitch.

I think I actually understand why this is happening (some interpreter magic around super() forcing the insertion of __class__, which that doesn't happen when parsing a stand-alone function). I think I even understand the rationale for it, which is that super() needs to be statically evaluated.

Now to the question though: In theory this information (static type of 'self' at the point of method binding to class) is available at the point of method injection, in this example, the next-to-last line of the code. So, is there a way to somehow inject/override/magically-make-it-appear the __class__ cell in 'method' such that super() starts working as expected again?

Thanks,
Andras Tantos



--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to