Python types.FunctionType() Examples
The following are 30
code examples of types.FunctionType().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
types
, or try the search function
.
Example #1
Source File: cloudpickle.py From pywren-ibm-cloud with Apache License 2.0 | 8 votes |
def _make_skel_func(code, cell_count, base_globals=None): """ Creates a skeleton function object that contains just the provided code and the correct number of cells in func_closure. All other func attributes (e.g. func_globals) are empty. """ # This is backward-compatibility code: for cloudpickle versions between # 0.5.4 and 0.7, base_globals could be a string or None. base_globals # should now always be a dictionary. if base_globals is None or isinstance(base_globals, str): base_globals = {} base_globals['__builtins__'] = __builtins__ closure = ( tuple(_make_empty_cell() for _ in range(cell_count)) if cell_count >= 0 else None ) return types.FunctionType(code, base_globals, None, None, closure)
Example #2
Source File: recipe_api.py From recipes-py with Apache License 2.0 | 6 votes |
def __new__(mcs, name, bases, attrs): """Automatically wraps all methods of subclasses of RecipeApi with @infer_composite_step. This allows defer_results to work as intended without manually decorating every method. """ wrap = lambda f: infer_composite_step(f) if f else f for attr in attrs: if attr in RecipeApiMeta.WHITELIST: continue val = attrs[attr] if isinstance(val, types.FunctionType): attrs[attr] = wrap(val) elif isinstance(val, property): attrs[attr] = property( wrap(val.fget), wrap(val.fset), wrap(val.fdel), val.__doc__) return super(RecipeApiMeta, mcs).__new__(mcs, name, bases, attrs)
Example #3
Source File: yacc.py From SublimeKSP with GNU General Public License v3.0 | 6 votes |
def get_pfunctions(self): p_functions = [] for name, item in self.pdict.items(): if not name.startswith('p_'): continue if name == 'p_error': continue if isinstance(item,(types.FunctionType,types.MethodType)): line = func_code(item).co_firstlineno module = inspect.getmodule(item) p_functions.append((line,module,name,item.__doc__)) # Sort all of the actions by line number p_functions.sort() self.pfuncs = p_functions # Validate all of the p_functions
Example #4
Source File: yacc.py From SublimeKSP with GNU General Public License v3.0 | 6 votes |
def validate_error_func(self): if self.error_func: if isinstance(self.error_func,types.FunctionType): ismethod = 0 elif isinstance(self.error_func, types.MethodType): ismethod = 1 else: self.log.error("'p_error' defined, but is not a function or method") self.error = 1 return eline = func_code(self.error_func).co_firstlineno efile = func_code(self.error_func).co_filename module = inspect.getmodule(self.error_func) self.modules[module] = 1 argcount = func_code(self.error_func).co_argcount - ismethod if argcount != 1: self.log.error("%s:%d: p_error() requires 1 argument",efile,eline) self.error = 1 # Get the tokens map
Example #5
Source File: helpers.py From moler with BSD 3-Clause "New" or "Revised" License | 6 votes |
def call_base_class_method_with_same_name(obj): """ Run base class method. :param obj: class object which methods will be decorated. :return: class object with decorated methods """ if hasattr(obj, "__dict__"): if obj.__dict__.items(): for attributeName in dir(obj): attribute = getattr(obj, attributeName) if "_decorate" in dir(attribute): if isinstance(attribute, (FunctionType, MethodType)): setattr(obj, attributeName, _wrapper(method=attribute, obj=obj)) return obj
Example #6
Source File: pools.py From python-pool-performance with MIT License | 6 votes |
def run_test(work_type: FunctionType, job_sets: Sequence, trials: int, pool_class: type, worker_count: int) -> Mapping: pool = pool_class(worker_count) if work_type == 'compute': test_func = pool.run_compute_test elif work_type == 'network': test_func = pool.run_network_test else: raise Exception("Invalid work type: {}".format(work_type)) results = map( lambda jobs: test_func(jobs, trials, show_progress=True), tqdm(job_sets, desc=pool_class.__name__), ) summarized_results = list(map(summarize_test, results)) pool.destroy_pool() return summarized_results
Example #7
Source File: moler_test.py From moler with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _decorate(obj=None, check_steps_end=False): # check that decorated function is not statimethod or classmethod if not obj: raise ExecutionException("Decorator for 'staticmethod' or 'classmethod' not implemented yet.", ) if hasattr(obj, "__dict__"): if obj.__dict__.items(): for attributeName in dir(obj): if attributeName == "_already_decorated": break attribute = getattr(obj, attributeName) if not attributeName.startswith("_"): if isinstance(attribute, (FunctionType, MethodType)): setattr(obj, attributeName, MolerTest._wrapper(attribute, check_steps_end=check_steps_end)) else: obj = MolerTest._wrapper(obj, check_steps_end=check_steps_end) else: raise ExecutionException("No '__dict__' in decorated object.") return obj
Example #8
Source File: base.py From ripozo with GNU General Public License v2.0 | 6 votes |
def test_get_apimethods(self): """ Tests that the function _get_apimethods appropriately gets apimethods and that they are class methods not _apiclassmethod instances. """ class MyResource(ResourceBase): @apimethod(methods=['GET']) @apimethod(methods=['POST']) def fake1(cls): pass @apimethod(route='/hey', methods=['GET']) def fake2(self): pass names = [] for name, clsmethod in _get_apimethods(MyResource): names.append(name) self.assertIsInstance(clsmethod, types.FunctionType) self.assertIn('fake1', names) self.assertIn('fake2', names) self.assertEqual(len(names), 2)
Example #9
Source File: FucStr.py From Jtyoui with MIT License | 6 votes |
def string_function(module: [str, ModuleType], func: str, *args, **kwargs): """根据字符串方法名来进行调用模块方法 :param module: 模块名 :param func: 模块中的方法名字 :param args: 方法里面的参数值 :param kwargs: 方法里面的参数值 :return: 返回一个返回值 """ if isinstance(module, ModuleType): if hasattr(module, func): func_or_var = getattr(module, func) if isinstance(func_or_var, FunctionType): return func_or_var(*args, **kwargs) else: return func_or_var else: print(f'{func}不是一个方法') elif isinstance(module, str): m = __import__(module) return string_function(m, func, *args, **kwargs) else: print(f'{module}不是一个模块') return None
Example #10
Source File: yacc.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def get_pfunctions(self): p_functions = [] for name, item in self.pdict.items(): if not name.startswith('p_') or name == 'p_error': continue if isinstance(item, (types.FunctionType, types.MethodType)): line = getattr(item, 'co_firstlineno', item.__code__.co_firstlineno) module = inspect.getmodule(item) p_functions.append((line, module, name, item.__doc__)) # Sort all of the actions by line number; make sure to stringify # modules to make them sortable, since `line` may not uniquely sort all # p functions p_functions.sort(key=lambda p_function: ( p_function[0], str(p_function[1]), p_function[2], p_function[3])) self.pfuncs = p_functions # Validate all of the p_functions
Example #11
Source File: _always_seq.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
def always_seq(edge, reset): callinfo = _getCallInfo() sigargs = [] if not isinstance(edge, _WaiterList): raise AlwaysSeqError(_error.EdgeType) edge.sig._read = True edge.sig._used = True sigargs.append(edge.sig) if reset is not None: if not isinstance(reset, ResetSignal): raise AlwaysSeqError(_error.ResetType) reset._read = True reset._used = True sigargs.append(reset) sigdict = _get_sigdict(sigargs, callinfo.symdict) def _always_seq_decorator(func): if not isinstance(func, FunctionType): raise AlwaysSeqError(_error.ArgType) if _isGenFunc(func): raise AlwaysSeqError(_error.ArgType) if func.__code__.co_argcount > 0: raise AlwaysSeqError(_error.NrOfArgs) return _AlwaysSeq(func, edge, reset, callinfo=callinfo, sigdict=sigdict) return _always_seq_decorator
Example #12
Source File: _always.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
def always(*args): callinfo = _getCallInfo() sigargs = [] for arg in args: if isinstance(arg, _Signal): arg._read = True arg._used = True sigargs.append(arg) elif isinstance(arg, _WaiterList): arg.sig._read = True arg.sig._used = True sigargs.append(arg.sig) elif not isinstance(arg, delay): raise AlwaysError(_error.DecArgType) sigdict = _get_sigdict(sigargs, callinfo.symdict) def _always_decorator(func): if not isinstance(func, FunctionType): raise AlwaysError(_error.ArgType) if _isGenFunc(func): raise AlwaysError(_error.ArgType) if func.__code__.co_argcount > 0: raise AlwaysError(_error.NrOfArgs) return _Always(func, args, callinfo=callinfo, sigdict=sigdict) return _always_decorator
Example #13
Source File: cloudpickle.py From pywren-ibm-cloud with Apache License 2.0 | 6 votes |
def save_pypy_builtin_func(self, obj): """Save pypy equivalent of builtin functions. PyPy does not have the concept of builtin-functions. Instead, builtin-functions are simple function instances, but with a builtin-code attribute. Most of the time, builtin functions should be pickled by attribute. But PyPy has flaky support for __qualname__, so some builtin functions such as float.__new__ will be classified as dynamic. For this reason only, we created this special routine. Because builtin-functions are not expected to have closure or globals, there is no additional hack (compared the one already implemented in pickle) to protect ourselves from reference cycles. A simple (reconstructor, newargs, obj.__dict__) tuple is save_reduced. Note also that PyPy improved their support for __qualname__ in v3.6, so this routing should be removed when cloudpickle supports only PyPy 3.6 and later. """ rv = (types.FunctionType, (obj.__code__, {}, obj.__name__, obj.__defaults__, obj.__closure__), obj.__dict__) self.save_reduce(*rv, obj=obj)
Example #14
Source File: yacc.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def validate_error_func(self): if self.error_func: if isinstance(self.error_func, types.FunctionType): ismethod = 0 elif isinstance(self.error_func, types.MethodType): ismethod = 1 else: self.log.error("'p_error' defined, but is not a function or method") self.error = True return eline = self.error_func.__code__.co_firstlineno efile = self.error_func.__code__.co_filename module = inspect.getmodule(self.error_func) self.modules.add(module) argcount = self.error_func.__code__.co_argcount - ismethod if argcount != 1: self.log.error('%s:%d: p_error() requires 1 argument', efile, eline) self.error = True # Get the tokens map
Example #15
Source File: __init__.py From pyGSTi with Apache License 2.0 | 6 votes |
def with_temp_path(filename=None): """Decorator version of ``IOBase.temp_path``""" arg_fn = None if isinstance(filename, types.FunctionType): # Decorator was used without calling, so `filename' is actually the decorated function arg_fn = filename filename = None def decorator(fn): @functools.wraps(fn) def inner(self, *args, **kwargs): with self.temp_path(filename) as tmp_path: return fn(self, tmp_path, *args, **kwargs) return inner if arg_fn is not None: return decorator(arg_fn) else: return decorator
Example #16
Source File: remote.py From LGWebOSRemote with MIT License | 6 votes |
def getCommands(cls): excludes = [ 'opened', 'closed', 'received_message', 'exec_command', 'getCommands' ] out = [] m = [x for x, y in cls.__dict__.items() if type(y) == FunctionType] for method in m: if method.startswith("_" + cls.__name__): continue if method in excludes: continue if method.startswith("__"): continue out.append(method) out.sort() return out
Example #17
Source File: grads.py From tangent with Apache License 2.0 | 6 votes |
def get_module_functions(modules): """Finds functions that do not have implemented derivatives. Args: modules: A list of Python modules. Functions contained in these modules will be checked for membership in 'implemented', and if not found, will be added to an 'unimplemented' set implemented: A Python object containing implemented derivatives. A function should be checkable for membership using the `fn in implemented` syntax. Returns: module_fns: A set of functions, builtins or ufuncs in `modules`. """ module_fns = set() for module in modules: for key in dir(module): attr = getattr(module, key) if isinstance( attr, (types.BuiltinFunctionType, types.FunctionType, numpy.ufunc)): module_fns.add(attr) return module_fns
Example #18
Source File: am.py From restrain-jit with MIT License | 5 votes |
def func_info(fn: types.FunctionType): return lambda vm: vm.code_info(fn)
Example #19
Source File: cy_jit.py From restrain-jit with MIT License | 5 votes |
def jit(self, f: FunctionType): func_info = self.get_func_info(f) code_info = func_info.r_codeinfo fn_place = self.allocate_place_for_function(code_info) fn_place.globals_from(func_info.r_globals) CodeEmit(self, code_info, fn_place) f = fn_place.function_module.f self.fn_place_index[id(f)] = fn_place return f
Example #20
Source File: base.py From tributary with Apache License 2.0 | 5 votes |
def __init__(self, *args, **kwargs): # the last thing we do is go through all of our methods and ensure that all `_callable_args` in our methods are replaced with nodes for meth in dir(self): meth = getattr(self, meth) if hasattr(meth, '_node_wrapper'): node = meth._node_wrapper if node is None: continue # modify in place in case used elsewhere for i, arg in enumerate(node._callable_args): if not isinstance(arg, Node): replace = getattr(self, arg) if not isinstance(replace, Node) and (isinstance(replace, types.FunctionType) or isinstance(replace, types.MethodType)): # call function to get node replace = replace() node._callable_args[i] = replace # modify in place in case used elsewhere for k, arg in node._callable_kwargs.items(): if not isinstance(arg, Node): replace = getattr(self, arg) if not isinstance(replace, Node) and (isinstance(replace, types.FunctionType) or isinstance(replace, types.MethodType)): # call function to get node replace = replace() node._callable_kwargs[k] = replace
Example #21
Source File: datatype.py From vulscan with MIT License | 5 votes |
def __deepcopy__(self, memo): retVal = self.__class__() memo[id(self)] = retVal for attr in dir(self): if not attr.startswith('_'): value = getattr(self, attr) if not isinstance(value, (types.BuiltinFunctionType, types.FunctionType, types.MethodType)): setattr(retVal, attr, copy.deepcopy(value, memo)) for key, value in self.items(): retVal.__setitem__(key, copy.deepcopy(value, memo)) return retVal
Example #22
Source File: lex.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def _form_master_re(relist, reflags, ldict, toknames): if not relist: return [] regex = '|'.join(relist) try: lexre = re.compile(regex, reflags) # Build the index to function map for the matching engine lexindexfunc = [None] * (max(lexre.groupindex.values()) + 1) lexindexnames = lexindexfunc[:] for f, i in lexre.groupindex.items(): handle = ldict.get(f, None) if type(handle) in (types.FunctionType, types.MethodType): lexindexfunc[i] = (handle, toknames[f]) lexindexnames[i] = f elif handle is not None: lexindexnames[i] = f if f.find('ignore_') > 0: lexindexfunc[i] = (None, None) else: lexindexfunc[i] = (None, toknames[f]) return [(lexre, lexindexfunc)], [regex], [lexindexnames] except Exception: m = int(len(relist)/2) if m == 0: m = 1 llist, lre, lnames = _form_master_re(relist[:m], reflags, ldict, toknames) rlist, rre, rnames = _form_master_re(relist[m:], reflags, ldict, toknames) return (llist+rlist), (lre+rre), (lnames+rnames) # ----------------------------------------------------------------------------- # def _statetoken(s,names) # # Given a declaration name s of the form "t_" and a dictionary whose keys are # state names, this function returns a tuple (states,tokenname) where states # is a tuple of state names and tokenname is the name of the token. For example, # calling this with s = "t_foo_bar_SPAM" might return (('foo','bar'),'SPAM') # -----------------------------------------------------------------------------
Example #23
Source File: sandbox.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def is_internal_attribute(obj, attr): """Test if the attribute given is an internal python attribute. For example this function returns `True` for the `func_code` attribute of python objects. This is useful if the environment method :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden. >>> from jinja2.sandbox import is_internal_attribute >>> is_internal_attribute(str, "mro") True >>> is_internal_attribute(str, "upper") False """ if isinstance(obj, types.FunctionType): if attr in UNSAFE_FUNCTION_ATTRIBUTES: return True elif isinstance(obj, types.MethodType): if attr in UNSAFE_FUNCTION_ATTRIBUTES or \ attr in UNSAFE_METHOD_ATTRIBUTES: return True elif isinstance(obj, type): if attr == 'mro': return True elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)): return True elif isinstance(obj, types.GeneratorType): if attr in UNSAFE_GENERATOR_ATTRIBUTES: return True elif hasattr(types, 'CoroutineType') and isinstance(obj, types.CoroutineType): if attr in UNSAFE_COROUTINE_ATTRIBUTES: return True elif hasattr(types, 'AsyncGeneratorType') and isinstance(obj, types.AsyncGeneratorType): if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES: return True return attr.startswith('__')
Example #24
Source File: metaclass_test.py From custom_inherit with MIT License | 5 votes |
def test_staticmethod2(): assert isinstance(Kid2.static, FunctionType) assert getdoc(Kid2.static) == "valid"
Example #25
Source File: metaclass_test.py From custom_inherit with MIT License | 5 votes |
def test_staticmethod(): assert isinstance(Kid().static, FunctionType) assert getdoc(Kid.static) == "valid"
Example #26
Source File: decorator_test.py From custom_inherit with MIT License | 5 votes |
def test_staticmethod(): assert isinstance(Kid.static, FunctionType) assert getdoc(Kid.static) == "valid"
Example #27
Source File: sandbox.py From recruit with Apache License 2.0 | 5 votes |
def is_internal_attribute(obj, attr): """Test if the attribute given is an internal python attribute. For example this function returns `True` for the `func_code` attribute of python objects. This is useful if the environment method :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden. >>> from jinja2.sandbox import is_internal_attribute >>> is_internal_attribute(str, "mro") True >>> is_internal_attribute(str, "upper") False """ if isinstance(obj, types.FunctionType): if attr in UNSAFE_FUNCTION_ATTRIBUTES: return True elif isinstance(obj, types.MethodType): if attr in UNSAFE_FUNCTION_ATTRIBUTES or \ attr in UNSAFE_METHOD_ATTRIBUTES: return True elif isinstance(obj, type): if attr == 'mro': return True elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)): return True elif isinstance(obj, types.GeneratorType): if attr in UNSAFE_GENERATOR_ATTRIBUTES: return True elif hasattr(types, 'CoroutineType') and isinstance(obj, types.CoroutineType): if attr in UNSAFE_COROUTINE_ATTRIBUTES: return True elif hasattr(types, 'AsyncGeneratorType') and isinstance(obj, types.AsyncGeneratorType): if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES: return True return attr.startswith('__')
Example #28
Source File: _inspect.py From recruit with Apache License 2.0 | 5 votes |
def isfunction(object): """Return true if the object is a user-defined function. Function objects provide these attributes: __doc__ documentation string __name__ name with which this function was defined func_code code object containing compiled function bytecode func_defaults tuple of any default values for arguments func_doc (same as __doc__) func_globals global namespace in which this function was defined func_name (same as __name__) """ return isinstance(object, types.FunctionType)
Example #29
Source File: html5parser.py From recruit with Apache License 2.0 | 5 votes |
def method_decorator_metaclass(function): class Decorated(type): def __new__(meta, classname, bases, classDict): for attributeName, attribute in classDict.items(): if isinstance(attribute, types.FunctionType): attribute = function(attribute) classDict[attributeName] = attribute return type.__new__(meta, classname, bases, classDict) return Decorated
Example #30
Source File: lex.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def _form_master_re(relist, reflags, ldict, toknames): if not relist: return [] regex = '|'.join(relist) try: lexre = re.compile(regex, reflags) # Build the index to function map for the matching engine lexindexfunc = [None] * (max(lexre.groupindex.values()) + 1) lexindexnames = lexindexfunc[:] for f, i in lexre.groupindex.items(): handle = ldict.get(f, None) if type(handle) in (types.FunctionType, types.MethodType): lexindexfunc[i] = (handle, toknames[f]) lexindexnames[i] = f elif handle is not None: lexindexnames[i] = f if f.find('ignore_') > 0: lexindexfunc[i] = (None, None) else: lexindexfunc[i] = (None, toknames[f]) return [(lexre, lexindexfunc)], [regex], [lexindexnames] except Exception: m = int(len(relist)/2) if m == 0: m = 1 llist, lre, lnames = _form_master_re(relist[:m], reflags, ldict, toknames) rlist, rre, rnames = _form_master_re(relist[m:], reflags, ldict, toknames) return (llist+rlist), (lre+rre), (lnames+rnames) # ----------------------------------------------------------------------------- # def _statetoken(s,names) # # Given a declaration name s of the form "t_" and a dictionary whose keys are # state names, this function returns a tuple (states,tokenname) where states # is a tuple of state names and tokenname is the name of the token. For example, # calling this with s = "t_foo_bar_SPAM" might return (('foo','bar'),'SPAM') # -----------------------------------------------------------------------------