def _deserialize_func(funcs, globalDict): items = pickle.loads(funcs) res = None for objType, name, data in items: if objType == 'func': codeArgs, funcArgs, updatedGlobals = pickle.loads(data) code = CodeType(*codeArgs) globalDict.update(**updatedGlobals) value = FunctionType(code, globalDict, *funcArgs) elif objType == 'mod': value = __import__(data) elif objType == 'oldclass': class_name, module, bases, class_dict = data value = typesmod.ClassType(class_name, bases, {k:_deserialize_func(v, globalDict) for k, v in class_dict.items()}) value.__module__ = module elif objType == 'type': raise Exception('deserialize type') else: raise Exception('Unknown serialization type') globalDict[name] = value if res is None: res = value return res
def wrap(**kwargs): injected = [ param.name for param in signature.parameters.values() if param.name not in kwargs and param.default is inspect._empty ] args = [f"{arg}={arg}" for arg in injected + list(kwargs.keys())] provider = f"def provide_{name}(self, {', '.join(injected)}): return prototype({', '.join(args)})" provider = FunctionType( compile(provider, "<string>", "exec").co_consts[0], { **kwargs, "prototype": prototype }, f"provide_{name}", ) provider.__module__ = "__main__" binding = type( f"Partial{prototype.__name__}Binding", (pinject.BindingSpec, ), { f"provide_{name}": provider, "__repr__": lambda self: f"{name}->{prototype.__name__}", }, )() binding.name = name return binding
def FactoryBindingSpec(name, prototype): r""" Return a BindingSpec that calls ``prototype`` as a provider for ``name``. EXAMPLES:: >>> def create(dependency): return 1337 >>> binding = FactoryBindingSpec("object", create) >>> inspect.signature(binding.provide_object) <Signature (dependency)> """ from types import FunctionType signature = inspect.signature(prototype) args = [param for param in signature.parameters.keys()] provider = f"def provide_{name}(self, {', '.join(args)}): return prototype({', '.join(args)})" provider = FunctionType( compile(provider, "<string>", "exec").co_consts[0], {"prototype": prototype}, f"provide_{name}", ) provider.__module__ = "__main__" binding = type( f"{name}FactoryBinding", (pinject.BindingSpec, ), { f"provide_{name}": provider, "__repr__": lambda self: f"{name}->{prototype}" }, )() binding.name = name return binding
def copy_func(func: FunctionType, deep: bool = False) -> FunctionType: """Copy a function as a different object. Args: func: Function object to be copied. deep: If ``True``, mutable attributes of ``func`` are deep-copied. Returns: Function as a different object from the original one. """ copied = FunctionType( func.__code__, func.__globals__, func.__name__, func.__defaults__, func.__closure__, ) # mutable attributes are copied by the given method copier = deepcopy if deep else copy copied.__annotations__ = copier(func.__annotations__) copied.__dict__ = copier(func.__dict__) copied.__kwdefaults__ = copier(func.__kwdefaults__) # immutable attributes are not copied (just assigned) copied.__doc__ = func.__doc__ copied.__module__ = func.__module__ copied.__name__ = func.__name__ copied.__qualname__ = func.__qualname__ return copied
def _create_function(fcode, fglobals, fname=None, fdefaults=None, fclosure=None, fdict=None, mod_name=None): # same as FunctionType, but enable passing __dict__ to new function, # __dict__ is the storehouse for attributes added after function creation log.info('loading function: ' + fname) fdict = fdict or dict() fglobals = fglobals or {} func = FunctionType(fcode, fglobals, fname, fdefaults, fclosure) func.__dict__.update(fdict) func.__module__ = mod_name return func
def fake_import(fake_module): module_name = 'martiantest.fake.' + fake_module.__name__ module = ModuleType(module_name) module_name_parts = module_name.split('.') module.__file__ = '/' + '/'.join(module_name_parts) glob = {} for name in dir(fake_module): if name.startswith('__') and '.' not in name: continue obj = getattr(fake_module, name) glob[name] = obj try: obj = obj.im_func except AttributeError: pass __module__ = None try: __module__ == obj.__dict__.get('__module__') except AttributeError: try: __module__ = obj.__module__ except AttributeError: pass if __module__ is None or __module__ == '__builtin__': try: obj.__module__ = module.__name__ except AttributeError: pass setattr(module, name, obj) # provide correct globals for functions for name in dir(module): if name.startswith('__'): continue obj = getattr(module, name) try: code = obj.__code__ new_func = FunctionType(code, glob, name) new_func.__module__ = module.__name__ setattr(module, name, new_func) glob[name] = new_func except AttributeError: pass if not 'martiantest' in sys.modules: sys.modules['martiantest'] = ModuleType('martiantest') sys.modules['martiantest.fake'] = ModuleType('martiantest.fake') sys.modules['martiantest'].fake = sys.modules['martiantest.fake'] sys.modules[module_name] = module setattr(sys.modules['martiantest.fake'], module_name.split('.')[-1], module) return module
def _function_constructor(code, fglobals, name, argdefs, closure, kwdefaults, fdict, annotations, qualname, doc, module): func = FunctionType(code, fglobals, name, argdefs, closure) func.__kwdefaults__ = kwdefaults func.__dict__ = fdict func.__annotations__ = annotations func.__qualname__ = qualname func.__doc__ = doc func.__module__ = module return func
def interactive(f): """decorator for making functions appear as interactively defined. This results in the function being linked to the user_ns as globals() instead of the module globals(). """ # build new FunctionType, so it can have the right globals # interactive functions never have closures, that's kind of the point if isinstance(f, FunctionType): mainmod = __import__("__main__") f = FunctionType(f.__code__, mainmod.__dict__, f.__name__, f.__defaults__) # associate with __main__ for uncanning f.__module__ = "__main__" return f
def interactive(f): """decorator for making functions appear as interactively defined. This results in the function being linked to the user_ns as globals() instead of the module globals(). """ # build new FunctionType, so it can have the right globals # interactive functions never have closures, that's kind of the point if isinstance(f, FunctionType): mainmod = __import__('__main__') f = FunctionType(f.__code__, mainmod.__dict__, f.__name__, f.__defaults__, ) # associate with __main__ for uncanning f.__module__ = '__main__' return f
def ListBindingSpec(name, sequence): r""" Return a BindingSpec that provides the instances of the types in ``sequence`` as a list. EXAMPLES:: >>> class SomeDependency: pass >>> class AnotherDependency: pass >>> binding = ListBindingSpec("list", [SomeDependency, AnotherDependency]) >>> inspect.signature(binding.provide_list) <Signature (some_dependency, another_dependency)> """ from types import FunctionType args = [ pinject.bindings.default_get_arg_names_from_class_name(typ.__name__)[0] for typ in sequence ] provider = ( f"def provide_{name}(self, {', '.join(args)}): return [{', '.join(args)}]" ) provider = FunctionType( compile(provider, "<string>", "exec").co_consts[0], {}, f"provide_{name}") provider.__module__ = "__main__" binding = type( f"{name}ListBinding", (pinject.BindingSpec, ), { f"provide_{name}": provider, "__repr__": lambda self: f"{name}->{sequence}" }, )() binding.name = name return binding
def func2not_implemented(func): sig_str = func2clean_signature_str(func) if sig_str not in cache__sig_str2code: code = signature_str2not_implemented_func(sig_str).__code__ cache__sig_str2code[sig_str] = code # code really depends on sig_str #cache__not_implemented_codes.add(code) #print('cache__not_implemented_codes', len(cache__not_implemented_codes)) else: code = cache__sig_str2code[sig_str] code_without_freevars = _replace_codestring(func.__code__, code) new = FunctionType(code_without_freevars, globals()) new.__dict__.update(vars(func)) new.__defaults__ = func.__defaults__ new.__kwdefaults__ = func.__kwdefaults__ new.__doc__ = func.__doc__ new.__name__ = func.__name__ new.__qualname__ = func.__qualname__ new.__module__ = func.__module__ new.__annotations__ = func.__annotations__ new.__dict__ = dict(func.__dict__) return new set_func_not_implemented(func) return func
def rebuild_func( func, cls=None, *wrappers, defaults_copy=None, kwdefaults_copy=None, dict_copy=None, closure_copy=None, global_ns=None, name=None, qualname=None, module=False, doc=False, annotations=False, ): """Create a copy of `func` that can be used as a method by any `cls` The main perk is giving a `cls` the ability to use *any* Python `function` as a bound method, regardless of where it was defined. In other words, it doesn't matter if a function was defined in the global scope, another module, or in the body of another class. Most importantly, functions that use zero-argument super will behave exactly the same as if they had been defined in `cls`. Unfortunately, there is one limitation. Wrapped functions not defined in the scope of a class body will not be able to use zero argument super. If they are wrapped *after* being bound with this function, they should have no problem working For convenience, any *wrappers provided will be applied after binding in the same order as decorator syntax, top to bottom or right to left ie. wrappers *(a, b ,c) will be equivalent to a(b(c(func))) There are nearly limitless uses for this black magic, but some good examples are the ability to make true deepcopies of functions, changing default/kwonly defaults, and tricking functions into using global references to objects not in the module it was defined in. To simplify the application of making true deepcopies of functions, which requires deepcopying of the original function's mutable attributes: __defaults__, __kwdefaults__, __dict__, and __closure__, the arguments `defaults_copy`, `kwdefaults_copy, `dict_copy`, and `closure_copy`, respectively, accept a callable that takes a single argument (the object to be copied) and returns an object of the same type (and length if applicable) to the original. If `defaults_copy` and `kwdefaults_copy` return None, the new function will no longer have default values. Otherwise, shallow copies of __defaults__, __kwdefaults__, and __dict__ are used, along with a deepcopy of __closure__. Parameters: :: `defaults_copy` called as defaults_copy(func.__defaults__) to replace `func.__defaults__`, the attribute that stores a tuple containing the default values of positional arguments. Removes default positional arguments entirely if it returns None :: `kwdefaults_copy` called as kwdefaults_copy(func.__kwdefaults__) to replace `func.__kwdefaults__`, the attribute that stores a mapping containing the default values of keyword only arguments. Removes default kwonly arguments entirely if it returns None :: `dict_copy` called as dict_copy(func.__dict__) to replace `func.__dict__` :: `closure_copy` called as closure_copy(func.__closure__) to replace `func.__closure__`, the attribute that stores references to any nonlocal names used by `func` :: `global_ns` used to replace func.__globals__ Will raise NameError if it doesn't contain all global references used by `func`. :: `name` a string that replaces func.__name__ :: `qualname` if None, will generate a new __qualname__ automatically, which depends on the values in `name`, `func`, and `cls` Otherwise, a string :: `module` can be any type and is used to replace `func.__module__` :: `doc` can be any type and is used to replace `func.__doc__` :: `annotations` None to clear or mapping to replace `func.__annotations__` By default is a shallow copy of `func.__annotations__` """ # validate func if not is_func(func): raise TypeError('func must be function object') else: f = func # validate cls if cls is None: class_was_not_none = False elif not is_heap_type(cls): raise TypeError('cls must be None or a Python class') else: class_was_not_none = True # validate defaults_copy defaults = f.__defaults__ if defaults_copy is None: defaults = None if defaults is None else tuple_copy(defaults) elif not callable(defaults_copy): raise TypeError('defaults_copy must be a callable') else: defaults = defaults_copy(defaults) # validate kwdefaults_copy kwdefaults = f.__kwdefaults__ if kwdefaults_copy is None: kwdefaults = None if kwdefaults is None else {**kwdefaults} elif not callable(kwdefaults_copy): raise TypeError('kwdefaults_copy must be a callable') else: kwdefaults = kwdefaults_copy(kwdefaults) # validate dict_copy new_dict = descriptor_getattr(f, '__dict__') if dict_copy is None: new_dict = {**new_dict} elif not callable(dict_copy): raise TypeError('dict_copy must be a callable') else: new_dict = dict_copy(new_dict) # validate closure_copy closure = f.__closure__ if closure_copy is None: if is_tuple(closure): closure = deepcopy_closure(closure) elif not callable(closure_copy): raise TypeError('closure_copy must be a callable') else: closure = closure_copy(closure) # validate name if name is None: name = f.__name__ elif not is_str(name): raise TypeError('function __name__ must be a string') # validate qualname if qualname is None: qualname = f'{cls.__name__}.{name}' if class_was_not_none else name elif not is_str(qualname): raise TypeError('function __qualname__ must be a string') # validate annotations f_annotations = f.__annotations__ if annotations is False: annotations = None if f_annotations is None else {**f_annotations} elif not is_mapping(annotations): raise TypeError('annotations must be None or a mapping') # validate global_ns sentinel = object() if global_ns is None: global_ns = f.__globals__ elif not is_dict(global_ns): raise TypeError('function __globals__ must be a dict') builtins = global_ns.get('__builtins__', sentinel) if builtins is sentinel: builtin_ns = {} elif is_dict(builtins): builtin_ns = builtins # the only time __builtins__ can be a module is if it IS builtins elif builtins is _builtins: builtin_ns = builtins.__dict__ else: raise TypeError('f.__globals__["__builtins__"] must be a dict' f'or the "builtins" module, not {builtins!r}') missing = set() code = f.__code__ co_freevars = code.co_freevars co_flags = code.co_flags co_names = code.co_names co_code = code.co_code for co_name in co_names: if iskeyword(co_name): continue ob = global_ns.get(co_name, sentinel) if ob is sentinel: ob = builtin_ns.get(co_name, sentinel) if ob is sentinel: if class_was_not_none and co_name == '__class__': continue missing.add(co_name) module = f.__module__ if module is False else module doc = f.__doc__ if doc is False else module if class_was_not_none: has_classcell = 'super' in co_names # replace LOAD_GLOBAL('__class__') opcodes with LOAD_DEREF('__class__') if '__class__' in co_names: j = co_names.index('__class__') #co_names = co_names[:j] + co_names[j+1:] bytecode = bytearray(co_code) for instr in dis.Bytecode(code): if instr.opname == 'LOAD_GLOBAL' and instr.argval == '__class__': has_classcell = True closure = closure or () i = len(closure) # if len(closure) >= 256, # the LOAD_DEREF opcode will use EXTENDED_ARG if i > 255: repl = b'\x90\x01\x88' + i.to_bytes(3, 'little') else: repl = b'\x88' + i.to_bytes(1, 'little') x = instr.offset bytecode[x:x + 2] = repl co_code = bytes(bytecode) # only add a class cell if necessary if has_classcell: cell = build_class_cell(cls) closure = closure or () # insert/replace the __class__ cell if it is already in freevars if '__class__' in co_freevars: i = co_freevars.index('__class__') j = len(closure) == len(co_freevars) closure = (*closure[:i], cell, *closure[i + j:]) # add if it doesn't else: co_freevars += ('__class__', ) closure += (cell, ) # ensure NOFREE flag is set if there are no frevars if not co_freevars: co_flags = (co_flags | NOFREE) if f.__closure__ is not None: raise TypeError('function closure was a tuple when its' 'code.co_freevars was empty') # since python 3.6, the NOFREE flag actually does what it's # supposed to do, so it must be unset to enable access of __closure__ else: co_flags = (co_flags | NOFREE) ^ NOFREE code = update_code(code, freevars=co_freevars, flags=co_flags, names=co_names, code=co_code) method = FunctionType(code, global_ns, closure=closure) method.__defaults__ = defaults method.__kwdefaults__ = kwdefaults method.__name__ = name method.__qualname__ = qualname method.__annotations__ = annotations method.__module__ = module method.__doc__ = doc FunctionType.__dict__['__dict__'].__set__(method, new_dict) for wrapper in reversed(wrappers): method = wrapper(method) return method