Author bup
Recipients bup
Date 2017-11-30.07:39:34
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1512027575.04.0.213398074469.issue32176@psf.upfronthosting.co.za>
In-reply-to
Content
The following code works in 3.3, 3.4, and 3.5, but in 3.6 it throws  RuntimeError: super(): bad __class__ cell. 

from types import FunctionType, CodeType

def create_closure(__class__):
    return (lambda: __class__).__closure__

def new_code(c_or_f):
    '''A new code object with a __class__ cell added to freevars'''
    c = c_or_f.__code__ if isinstance(c_or_f, FunctionType) else c_or_f
    return 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)

def add_foreign_method(cls, f):
    code = new_code(f.__code__)
    name = f.__name__
    defaults = f.__defaults__
    closure = (f.__closure__ or ()) + create_closure(cls)
    setattr(cls, name, FunctionType(code, globals(), name, defaults, closure))

class List(list):
    def append(self, elem):
        super().append(elem)
    def extend(self, elems):
        super().extend(elems)
def __getitem__(self, i):
    print('foreign getitem')
    return super().__getitem__(i)

add_foreign_method(List, __getitem__)

self = List([1,2,3])
self[0]
History
Date User Action Args
2017-11-30 07:39:35bupsetrecipients: + bup
2017-11-30 07:39:35bupsetmessageid: <1512027575.04.0.213398074469.issue32176@psf.upfronthosting.co.za>
2017-11-30 07:39:34buplinkissue32176 messages
2017-11-30 07:39:34bupcreate