Skip to content

Instantly share code, notes, and snippets.

@cosmin
Created January 6, 2014 05:59
Show Gist options
  • Save cosmin/8278872 to your computer and use it in GitHub Desktop.
Save cosmin/8278872 to your computer and use it in GitHub Desktop.
Function to create a new class using a base class with substituted global scope
import types
def clone(original, **newg):
return types.FunctionType(original.func_code,
dict(original.func_globals, **newg),
original.func_name,
original.func_defaults,
original.func_closure)
def inject(cls, **newg):
newdict = dict(cls.__dict__)
for methodname,func in cls.__dict__.items():
if isinstance(func, types.FunctionType):
for k in newg:
if k in func.func_code.co_names:
newdict[methodname] = clone(func, **newg)
break
return types.ClassType(cls.__name__, (cls, ), newdict)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment