本文整理汇总了Python中six.get_function_closure函数的典型用法代码示例。如果您正苦于以下问题:Python get_function_closure函数的具体用法?Python get_function_closure怎么用?Python get_function_closure使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_function_closure函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: _update_function
def _update_function(oldfunc, newfunc):
"""Update a function object."""
if _closure_changed(six.get_function_closure(oldfunc),
six.get_function_closure(newfunc)):
raise ClosureChanged()
setattr(oldfunc, six._func_code, six.get_function_code(newfunc))
setattr(oldfunc, six._func_defaults, six.get_function_defaults(newfunc))
_update_scope(six.get_function_globals(oldfunc),
six.get_function_globals(newfunc))
# XXX What else?
return oldfunc
开发者ID:plone,项目名称:plone.reload,代码行数:11,代码来源:xreload.py
示例2: test_throttler
def test_throttler(self):
threshold = 1
orig_function = mock.Mock()
# Add this magic name as it's required by functools
orig_function.__name__ = 'mock_func'
throttled_func = utils.throttler(threshold)(orig_function)
throttled_func()
sleep = utils.eventlet.sleep
def sleep_mock(amount_to_sleep):
sleep(amount_to_sleep)
self.assertGreater(threshold, amount_to_sleep)
with mock.patch.object(utils.eventlet, "sleep",
side_effect=sleep_mock):
throttled_func()
self.assertEqual(2, orig_function.call_count)
lock_with_timer = six.get_function_closure(
throttled_func)[1].cell_contents
timestamp = lock_with_timer.timestamp - threshold
lock_with_timer.timestamp = timestamp
throttled_func()
self.assertEqual(3, orig_function.call_count)
self.assertLess(timestamp, lock_with_timer.timestamp)
开发者ID:igordcard,项目名称:neutron,代码行数:30,代码来源:test_utils.py
示例3: run_while
def run_while(cond_fn, body_fn, init_args):
"""Type-dependent functional while loop.
Args:
cond_fn: A Python callable implementing the stop conditions of the loop.
body_fn: A Python callable implementing the body of the loop.
init_args: The initial values of the arguments that will be passed to both
cond_fn and body_fn.
Returns:
result: A list of values with the same shape and type as init_args. If any
of the init_args, or any variables closed-over in cond_fn are Tensors,
tf.while_loop will be used, otherwise a Python while loop will be ran.
Raises:
ValueError: if init_args is not a tuple or list with one or more elements.
"""
if not isinstance(init_args, (tuple, list)) or not init_args:
raise ValueError(
'init_args must be a non-empty list or tuple, found %s' % init_args)
# TODO(alexbw): statically determine all active variables in cond_fn,
# and pass them directly
closure_vars = tuple(
[c.cell_contents for c in six.get_function_closure(cond_fn) or []])
possibly_tensors = tuple(init_args) + closure_vars
if is_tensor(*possibly_tensors):
return control_flow_ops.while_loop(cond_fn, body_fn, init_args)
else:
return py_while_loop(cond_fn, body_fn, init_args)
开发者ID:AndrewTwinz,项目名称:tensorflow,代码行数:30,代码来源:multiple_dispatch.py
示例4: inspect_function_closures
def inspect_function_closures(self, func):
if self.found_req and self.stop_on_request_find:
return
if not get_function_closure(func):
if self.logger:
self.logger.debug('Function does not have any closure, skipping')
return
closures = function_closure_dict(func)
if func.__name__ == 'inner' and function_module(func) == 'tornado.gen':
# We are inside tornado.gen.Runner.run, continue to actual wrapped generator
generator_obj = closures['self'].gen
gen_frame = generator_obj.gi_frame
if gen_frame: # frame may be empty
if self.logger:
self.logger.debug('Found `tornado.gen` instance, running: %s, has_frame: %s'
% (generator_obj.gi_running, bool(gen_frame)))
# why? need test
# if not generator_obj.gi_running:
# # only write this line as async calls if generator is NOT running, if it's running it's present
# # on the normal traceback
self.async_frames.append(gen_frame)
if self.logger:
self.logger.debug('Diving into `tornado.gen` frame: %s' % traceback.format_stack(gen_frame, 1)[0])
self.inspect_dict(gen_frame.f_locals)
elif self.logger:
self.logger.debug('Found dead `tornado.gen` instance (without any frame), skipping')
return # it's a `tornado.gen` object, not need to dive into closures
if self.logger:
self.logger.debug('Cannot find generator, diving into closure variables')
return self.inspect_dict(closures)
开发者ID:tahajahangir,项目名称:tornado-inspector,代码行数:31,代码来源:tornado_inspector.py
示例5: function_to_graph
def function_to_graph(f, conversion_map, param_value_hints, owner_type=None):
"""Specialization of `object_to_graph` for callable functions."""
node = parser.parse_object(f).body[0]
node_globals = six.get_function_globals(f)
# This is needed for non-global functions.
closure = six.get_function_closure(f)
if closure:
for e in closure:
if callable(e.cell_contents):
fn = e.cell_contents
node_globals[fn.__name__] = fn
namer = conversion_map.new_namer(node_globals)
node = node_to_graph(node, namer, node_globals, param_value_hints)
# Simulate a rename to ensure the top level is in the name map. This is needed
# for top level functions, and it also helps the consistency verification made
# by update_name_map.
if owner_type is not None:
new_name = namer.compiled_function_name(f.__name__, f, owner_type)
else:
new_name = namer.compiled_function_name(f.__name__, f)
node.name = new_name
conversion_map.update_name_map(namer)
return node, conversion_map.name_map[f]
开发者ID:andrewharp,项目名称:tensorflow,代码行数:26,代码来源:conversion.py
示例6: parse_args
def parse_args(args, path, query, specials):
def one_or_many(fn_, dict_, key):
result = [fn_(value) for value in dict_[key]]
return result[0] if len(result) == 1 else result
kwargs = {}
for arg, parse_fn in six.iteritems(args):
if arg in specials:
kwargs[arg] = specials[arg]()
elif parse_fn is None:
kwargs[arg] = one_or_many(lambda x: x, query, arg)
elif isinstance(parse_fn, tuple):
kwargs[arg] = parse_fn[DEFAULT] if arg not in query else one_or_many(parse_fn[CALLABLE], query, arg)
elif isalambda(parse_fn):
_code = six.get_function_code(parse_fn)
closures = six.get_function_closure(parse_fn)
if closures:
assert len(closures) <= 1
fn = closures[0].cell_contents
else:
fn = eval(".".join(_code.co_names), six.get_function_globals(parse_fn))
kwargs[arg] = fn(**parse_args(get_function_args(parse_fn), path, query, specials))
else:
kwargs[arg] = one_or_many(parse_fn, query, arg)
return kwargs
开发者ID:petr-s,项目名称:cleaREST,代码行数:25,代码来源:core.py
示例7: getrealname
def getrealname(method):
"""attempt to get a method's real name."""
argspec = inspect.getargspec(method)
args = argspec[0]
if args and args[0] == 'self':
return method.__name__
if hasattr(method, '__func__'):
method = method.__func__
func_closure = six.get_function_closure(method)
# NOTE(sileht): if the closure is None we cannot look deeper,
# so return actual argspec, this occurs when the method
# is static for example.
if func_closure is None:
return method.__name__
closure = next(
(
c for c in func_closure if six.callable(c.cell_contents)
),
None
)
method = closure.cell_contents
return getrealname(method)
开发者ID:shu-mutou,项目名称:pecan-swagger,代码行数:25,代码来源:g.py
示例8: function_to_graph
def function_to_graph(f, conversion_map, param_value_hints):
"""Specialization of `object_to_graph` for callable functions."""
node = parser.parse_object(f).body[0]
node_globals = six.get_function_globals(f)
# This is needed for non-global functions.
closure = six.get_function_closure(f)
if closure:
for e in closure:
if callable(e.cell_contents):
fn = e.cell_contents
node_globals[fn.__name__] = fn
namer = conversion_map.new_namer(node_globals)
node = node_to_graph(node, namer, node_globals, param_value_hints)
# Simulate a rename to ensure the top level is in the name map. This is needed
# for top level functions, and it also helps the consistency verification made
# by update_name_map.
namer.compiled_function_name(f.__name__, f)
conversion_map.add_to_cache(f, node)
conversion_map.update_name_map(namer)
# Recursively convert any remaining dependencies.
for obj in conversion_map.name_map.keys():
if obj not in conversion_map.dependency_cache:
object_to_graph(obj, conversion_map, None)
return node, conversion_map.name_map[f]
开发者ID:Lin-jipeng,项目名称:tensorflow,代码行数:29,代码来源:conversion.py
示例9: construct_new_test_function
def construct_new_test_function(original_func, name, build_params):
"""Builds a new test function based on parameterized data.
:param original_func: The original test function that is used as a template
:param name: The fullname of the new test function
:param build_params: A dictionary or list containing args or kwargs
for the new test
:return: A new function object
"""
new_func = types.FunctionType(
six.get_function_code(original_func),
six.get_function_globals(original_func),
name=name,
argdefs=six.get_function_defaults(original_func),
closure=six.get_function_closure(original_func)
)
for key, val in original_func.__dict__.items():
if key != 'build_data':
new_func.__dict__[key] = val
# Support either an arg list or kwarg dict for our data
build_args = build_params if isinstance(build_params, list) else []
build_kwargs = build_params if isinstance(build_params, dict) else {}
# Build a test wrapper to execute with our kwargs
def test_wrapper(func, test_args, test_kwargs):
@functools.wraps(func)
def wrapper(self):
return func(self, *test_args, **test_kwargs)
return wrapper
return test_wrapper(new_func, build_args, build_kwargs)
开发者ID:ktroach,项目名称:barbican,代码行数:33,代码来源:utils.py
示例10: get_wrapped_function
def get_wrapped_function(function):
"""Get the method at the bottom of a stack of decorators."""
if not hasattr(function, six._func_closure) or \
not six.get_function_closure(function):
return function
def _get_wrapped_function(function):
if not hasattr(function, six._func_closure):
return None
func_closure = six.get_function_closure(function)
if not func_closure:
return None
for closure in func_closure:
func = closure.cell_contents
deeper_func = _get_wrapped_function(func)
if deeper_func:
return deeper_func
elif hasattr(closure.cell_contents, '__call__'):
return closure.cell_contents
return _get_wrapped_function(function)
开发者ID:ChristopherMacGown,项目名称:oslo-incubator,代码行数:25,代码来源:funcutils.py
示例11: function_to_graph
def function_to_graph(f, conversion_map, arg_values, arg_types,
owner_type=None):
"""Specialization of `entity_to_graph` for callable functions."""
node = parser.parse_object(f).body[0]
namespace = six.get_function_globals(f)
# This is needed for non-global functions.
closure = six.get_function_closure(f)
if closure:
for e in closure:
if callable(e.cell_contents):
fn = e.cell_contents
namespace[fn.__name__] = fn
namer = conversion_map.new_namer(namespace)
ctx = context.EntityContext(
namer=namer,
source_code=tf_inspect.getsource(f),
source_file=tf_inspect.getfile(f),
namespace=namespace,
arg_values=arg_values,
arg_types=arg_types)
node = node_to_graph(node, ctx, conversion_map.nocompile_decorators)
# Simulate a rename to ensure the top level is in the name map. This is needed
# for top level functions, and it also helps the consistency verification made
# by update_name_map.
if owner_type is not None:
new_name = namer.compiled_function_name(f.__name__, f, owner_type)
else:
new_name = namer.compiled_function_name(f.__name__, f)
node.name = new_name
conversion_map.update_name_map(namer)
return node, conversion_map.name_map[f]
开发者ID:craffel,项目名称:tensorflow,代码行数:34,代码来源:conversion.py
示例12: getargspec
def getargspec(method):
"""
Drill through layers of decorators attempting to locate the actual argspec
for a method.
"""
argspec = inspect.getargspec(method)
args = argspec[0]
if args and args[0] == 'self':
return argspec
if hasattr(method, '__func__'):
method = method.__func__
func_closure = six.get_function_closure(method)
# NOTE(sileht): if the closure is None we cannot look deeper,
# so return actual argspec, this occurs when the method
# is static for example.
if func_closure is None:
return argspec
closure = next(
(
c for c in func_closure if six.callable(c.cell_contents)
),
None
)
method = closure.cell_contents
return getargspec(method)
开发者ID:SvenDowideit,项目名称:clearlinux,代码行数:29,代码来源:util.py
示例13: serialize
def serialize(cust_obj):
"""A function to serialize custom objects passed to a model
Args:
cust_obj(callable): a custom layer or function to serialize
Returns:
a dict of the serialized components of the object"""
ser_func = dict()
if isinstance(cust_obj, types.FunctionType):
func_code = six.get_function_code(cust_obj)
func_code_d = dill.dumps(func_code).decode('raw_unicode_escape')
ser_func['func_code_d'] = func_code_d
ser_func['name_d'] = pickle.dumps(
cust_obj.__name__).decode('raw_unicode_escape')
ser_func['args_d'] = pickle.dumps(
six.get_function_defaults(cust_obj)).decode('raw_unicode_escape')
clos = dill.dumps(
six.get_function_closure(cust_obj)).decode('raw_unicode_escape')
ser_func['clos_d'] = clos
ser_func['type_obj'] = 'func'
else:
if hasattr(cust_obj, '__module__'): # pragma: no cover
cust_obj.__module__ = '__main__'
ser_func['name_d'] = None
ser_func['args_d'] = None
ser_func['clos_d'] = None
ser_func['type_obj'] = 'class'
loaded = dill.dumps(cust_obj).decode('raw_unicode_escape')
ser_func['func_code_d'] = loaded
return ser_func
开发者ID:tboquet,项目名称:python-alp,代码行数:32,代码来源:keras_backend.py
示例14: _build_new_function
def _build_new_function(func, name):
code = six.get_function_code(func)
func_globals = six.get_function_globals(func)
func_defaults = six.get_function_defaults(func)
func_closure = six.get_function_closure(func)
return types.FunctionType(code, func_globals,
name, func_defaults,
func_closure)
开发者ID:stefan-caraiman,项目名称:cloudbase-init-ci,代码行数:8,代码来源:base.py
示例15: test_get_function_closure
def test_get_function_closure():
def f():
x = 42
def g():
return x
return g
cell = six.get_function_closure(f())[0]
assert type(cell).__name__ == "cell"
开发者ID:A-Maze,项目名称:A-Pc,代码行数:8,代码来源:test_six.py
示例16: _resolve_methods
def _resolve_methods(self):
import six
callback = self.pattern.callback
try:
closure = six.get_function_closure(callback)
code = six.get_function_code(callback)
while getattr(code, 'co_name') != 'view':
# lets unwrap!
view = getattr(closure[0], 'cell_contents')
closure = six.get_function_closure(view)
code = six.get_function_code(view)
freevars = code.co_freevars
except (AttributeError, IndexError):
raise RuntimeError('Unable to use callback invalid closure/function specified.')
else:
return closure[freevars.index('actions')].cell_contents
开发者ID:vinodc,项目名称:django-rest-swagger,代码行数:20,代码来源:introspectors.py
示例17: _resolve_methods
def _resolve_methods(self):
from rest_framework_swagger.decorators import unwrap_decorator
callback = self.pattern.callback
closure = six.get_function_closure(callback)
code = six.get_function_code(callback)
if code and code.co_name == 'wrapped_view':
closure, code = unwrap_decorator(callback)
try:
freevars = code.co_freevars
except AttributeError:
raise RuntimeError('Unable to use callback invalid closure/function specified.')
return closure[freevars.index('actions')].cell_contents
开发者ID:gotche,项目名称:django-rest-swagger,代码行数:13,代码来源:introspectors.py
示例18: __init__
def __init__(self):
self._cache_groups = dict()
self._diff_running = False
regex = re.compile(r'^_cache_(.+)$')
for (_, m) in inspect.getmembers(type(self),
predicate=lambda p:
(inspect.ismethod or
inspect.isdatadescriptor)):
if hasattr(m, 'fget'):
f = m.fget
elif inspect.ismethod(m):
f = six.get_method_function(m)
elif inspect.isfunction(m):
f = m
else:
continue
fv = six.get_function_code(f).co_freevars
try:
closure = six.get_function_closure(f)
except AttributeError:
continue
if closure is None:
continue
vs = dict(zip(fv, (c.cell_contents for c in closure)))
# this is used to make sure we are in the right function
# i'm not proud of that, by the way
if '_cache_identifier_pj97YCjgnp' not in vs:
continue
try:
groups = vs['groups']
method_name = re.match(regex, vs['cache_var_name']).group(1)
except KeyError:
continue
for g in groups:
if g not in self._cache_groups:
self._cache_groups[g] = []
self._cache_groups[g].append(method_name)
setattr(self, '_cache_' + method_name, None)
setattr(self, '_cached_' + method_name, False)
setattr(self, '_cached_args_' + method_name, dict())
开发者ID:PMBio,项目名称:limix,代码行数:51,代码来源:_hcache.py
示例19: fix_js_args
def fix_js_args(func):
'''Use this function when unsure whether func takes this and arguments as its last 2 args.
It will append 2 args if it does not.'''
fcode = six.get_function_code(func)
fargs = fcode.co_varnames[fcode.co_argcount - 2:fcode.co_argcount]
if fargs == ('this', 'arguments') or fargs == ('arguments', 'var'):
return func
code = append_arguments(six.get_function_code(func), ('this', 'arguments'))
return types.FunctionType(
code,
six.get_function_globals(func),
func.__name__,
closure=six.get_function_closure(func))
开发者ID:JackDandy,项目名称:SickGear,代码行数:14,代码来源:injector.py
示例20: copy_func
def copy_func(f, name=None):
"""Create a copy of a function.
Parameters
----------
f : function
Function to copy.
name : str, optional
Name of new function.
"""
return types.FunctionType(six.get_function_code(f),
six.get_function_globals(f), name or f.__name__,
six.get_function_defaults(f), six.get_function_closure(f))
开发者ID:ClinicalGraphics,项目名称:scikit-image,代码行数:14,代码来源:utils.py
注:本文中的six.get_function_closure函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论