本文整理汇总了Python中types.FunctionType方法的典型用法代码示例。如果您正苦于以下问题:Python types.FunctionType方法的具体用法?Python types.FunctionType怎么用?Python types.FunctionType使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类types
的用法示例。
在下文中一共展示了types.FunctionType方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_test
# 需要导入模块: import types [as 别名]
# 或者: from types import FunctionType [as 别名]
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
示例2: validate_error_func
# 需要导入模块: import types [as 别名]
# 或者: from types import FunctionType [as 别名]
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
示例3: get_pfunctions
# 需要导入模块: import types [as 别名]
# 或者: from types import FunctionType [as 别名]
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
示例4: default
# 需要导入模块: import types [as 别名]
# 或者: from types import FunctionType [as 别名]
def default(self, o):
if types.FunctionType == type(o):
return o.__name__
# sets become lists
if isinstance(o, set):
return list(o)
# date times become strings
if isinstance(o, datetime):
return o.isoformat()
if isinstance(o, decimal.Decimal):
return float(o)
if isinstance(o, type):
return str(o)
if isinstance(o, Exception):
return str(o)
if isinstance(o, set):
return str(o, 'utf-8')
if isinstance(o, bytes):
return str(o, 'utf-8')
return json.JSONEncoder.default(self, o)
示例5: always_seq
# 需要导入模块: import types [as 别名]
# 或者: from types import FunctionType [as 别名]
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
示例6: always
# 需要导入模块: import types [as 别名]
# 或者: from types import FunctionType [as 别名]
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
示例7: save_pypy_builtin_func
# 需要导入模块: import types [as 别名]
# 或者: from types import FunctionType [as 别名]
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)
示例8: _make_skel_func
# 需要导入模块: import types [as 别名]
# 或者: from types import FunctionType [as 别名]
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)
示例9: getCommands
# 需要导入模块: import types [as 别名]
# 或者: from types import FunctionType [as 别名]
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
示例10: get_module_functions
# 需要导入模块: import types [as 别名]
# 或者: from types import FunctionType [as 别名]
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
示例11: with_temp_path
# 需要导入模块: import types [as 别名]
# 或者: from types import FunctionType [as 别名]
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
示例12: validate_error_func
# 需要导入模块: import types [as 别名]
# 或者: from types import FunctionType [as 别名]
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
示例13: get_pfunctions
# 需要导入模块: import types [as 别名]
# 或者: from types import FunctionType [as 别名]
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
示例14: __new__
# 需要导入模块: import types [as 别名]
# 或者: from types import FunctionType [as 别名]
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)
示例15: string_function
# 需要导入模块: import types [as 别名]
# 或者: from types import FunctionType [as 别名]
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