本文整理汇总了Python中six.get_function_code函数的典型用法代码示例。如果您正苦于以下问题:Python get_function_code函数的具体用法?Python get_function_code怎么用?Python get_function_code使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_function_code函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_bakery_dynamic_attr
def _get_bakery_dynamic_attr(self, attname, obj, args=None, default=None):
"""
Allows subclasses to provide an attribute (say, 'foo') in three
different ways: As a fixed class-level property or as a method
foo(self) or foo(self, obj). The second argument argument 'obj' is
the "subject" of the current Feed invocation. See the Django Feed
documentation for details.
This method was shamelessly stolen from the Feed class and extended
with the ability to pass additional arguments to subclass methods.
"""
try:
attr = getattr(self, attname)
except AttributeError:
return default
if callable(attr) or args:
args = args[:] if args else []
# Check co_argcount rather than try/excepting the function and
# catching the TypeError, because something inside the function
# may raise the TypeError. This technique is more accurate.
try:
code = six.get_function_code(attr)
except AttributeError:
code = six.get_function_code(attr.__call__)
if code.co_argcount == 2 + len(args): # one argument is 'self'
args.append(obj)
return attr(*args)
return attr
示例2: __init__
def __init__(self, cb, args, kwargs):
self.callback = cb
self.args = args or []
self.kwargs = kwargs or {}
self.callback_name = cb.__name__
self.callback_filename = os.path.split(get_function_code(cb).co_filename)[-1]
self.callback_lineno = get_function_code(cb).co_firstlineno + 1
示例3: test_function_attached_as_workpace_method_has_same_metainformation_as_free_function
def test_function_attached_as_workpace_method_has_same_metainformation_as_free_function(self):
self.assertEqual(MatrixWorkspace.rebin.__name__, simpleapi.Rebin.__name__)
self.assertEqual(MatrixWorkspace.rebin.__doc__, simpleapi.Rebin.__doc__)
# Signature of method will have extra self argument
freefunction_sig = six.get_function_code(simpleapi.rebin).co_varnames
expected_method_sig = ['self']
expected_method_sig.extend(freefunction_sig)
self.assertEqual(six.get_function_code(MatrixWorkspace.rebin).co_varnames, tuple(expected_method_sig))
示例4: _func_type
def _func_type(func):
""" returns if callable is a function, method or a classmethod """
argnames = six.get_function_code(func).co_varnames[:six.get_function_code(func).co_argcount]
if len(argnames) > 0:
if argnames[0] == 'self':
return 'method'
if argnames[0] == 'cls':
return 'classmethod'
return 'function'
示例5: 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))
示例6: get_func_code
def get_func_code(func):
"""Returns func_code of passed callable."""
_, func = tf_decorator.unwrap(func)
if callable(func):
if tf_inspect.isfunction(func) or tf_inspect.ismethod(func):
return six.get_function_code(func)
elif hasattr(func, '__call__'):
return six.get_function_code(func.__call__)
else:
raise ValueError('Unhandled callable, type=%s' % type(func))
else:
raise ValueError('Argument must be callable')
示例7: __eq__
def __eq__(self, other):
if self.name != other.name:
return False
# Functions do not define __eq__ but func_code objects apparently do.
# (If we're wrapping some other callable, they will be responsible for
# defining equality on their end.)
if self.body == other.body:
return True
else:
try:
return six.get_function_code(self.body) == six.get_function_code(other.body)
except AttributeError:
return False
示例8: check_function_eq
def check_function_eq(func_a, func_b):
"""Check if two functions have the same bytecode."""
code_a = six.get_function_code(func_a)
code_b = six.get_function_code(func_b)
# check the equality of the bytecode
code_equality = all([getattr(code_a, prop) == getattr(code_b, prop) for
prop in _FUNCTION_EQUALITY_PROPERTIES])
# check the equality of the function
function_equality = all([func(func_b) == func(func_b) for func
in _FUNCTION_EQUALITY_METHODS])
return all([code_equality, function_equality])
示例9: 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
示例10: wrapped_target
def wrapped_target(*args, **kwargs):
with silk_meta_profiler():
try:
func_code = six.get_function_code(target)
except AttributeError:
raise NotImplementedError(
"Profile not implemented to decorate type %s" % target.__class__.__name__
)
line_num = func_code.co_firstlineno
file_path = func_code.co_filename
func_name = target.__name__
if not self.name:
self.name = func_name
self.profile = {
"func_name": func_name,
"name": self.name,
"file_path": file_path,
"line_num": line_num,
"dynamic": self._dynamic,
"start_time": timezone.now(),
"request": DataCollector().request,
}
self._start_queries()
try:
result = target(*args, **kwargs)
except Exception:
self.profile["exception_raised"] = True
raise
finally:
with silk_meta_profiler():
self.profile["end_time"] = timezone.now()
self._finalise_queries()
return result
示例11: attach_func_as_method
def attach_func_as_method(name, func_obj, self_param_name, workspace_types=None):
"""
Adds a method to the given type that calls an algorithm
using the calling object as the input workspace
:param name: The name of the new method as it should appear on the type
:param func_obj: A free function object that defines the implementation of the call
:param self_param_name: The name of the parameter in the free function that the method's self maps to
:param workspace_types: A list of string names of a workspace types. If None, then it is attached
to the general Workspace type. Default=None
"""
def _method_impl(self, *args, **kwargs):
# Map the calling object to the requested parameter
kwargs[self_param_name] = self
# Define the frame containing the final variable assignment
# used to figure out the workspace name
kwargs["__LHS_FRAME_OBJECT__"] = _inspect.currentframe().f_back
# Call main function
return func_obj(*args, **kwargs)
# ------------------------------------------------------------------
# Add correct meta-properties for the method
signature = ["self"]
signature.extend(get_function_code(func_obj).co_varnames)
customise_func(_method_impl, func_obj.__name__, tuple(signature), func_obj.__doc__)
if workspace_types or len(workspace_types) > 0:
for typename in workspace_types:
cls = getattr(_api, typename)
setattr(cls, name, _method_impl)
else:
setattr(_api.Workspace, name, _method_impl)
示例12: 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
示例13: __deepcopy__
def __deepcopy__(self, memo=None):
"""Create and return a deep copy of this instance."""
# Attempt to figure out from the method signature whether
# a comparison function is expected.
args = []
code = six.get_function_code(self.__class__.__init__)
if any([i.endswith('__cmp') for i in code.co_varnames]):
args.append(self._cmp)
# Create an empty sorted dictionary.
answer = self.__class__(*args)
# Ensure that this object is in our memo list, in case
# there is a recursive relationship.
if not memo:
memo = {}
memo[id(self)] = answer
# Deep copy the individual elements.
for key, value in six.iteritems(self):
answer.__setitem__(
deepcopy(key, memo=memo),
deepcopy(value, memo=memo),
)
# Done.
return answer
示例14: __call__
def __call__ (self, fn, instance, args, kwargs):
log_this = LOG.isEnabledFor (self.log_level)
if self.log_enter and log_this:
# Non-python methods don't have a func_code
if self.log_args and hasattr (fn, "func_code"):
code = six.get_function_code(fn)
argnames = code.co_varnames[:code.co_argcount]
x_args = args if not instance else ((instance,) + args)
arg_str = ", ".join ("%s=%r" % entry for entry in
list(zip (argnames, x_args))
+ list(kwargs.items ()))
else: # Why?
arg_str = "..."
LOG.log (self.log_level, "Called: %s:%s:%s (%s)",
fn.__class__.__name__,
getattr (fn, "__module__", "<?module?>"),
getattr (fn, "__name__", "<?name?>"),
arg_str)
if self.log_trace:
sys.settrace (self.globaltrace)
tic = time.time ()
rc = fn (*args, **kwargs)
toc = time.time ()
if self.log_trace:
sys.settrace (None)
if self.log_exit and log_this:
LOG.log (
self.log_level,
"Return: %s:%s:%s (...) -> %s (...) Duration: %.6f secs RC: %s",
fn.__class__.__name__,
getattr (fn, "__module__", "<?module?>"),
getattr (fn, "__name__", "<?name?>"),
inspect.currentframe ().f_back.f_code.co_name,
toc - tic, rc if self.log_rc else "...")
return rc
示例15: replot
def replot(plot,
agg=Count(), info=Const(val=1), shader=Id(),
remove_original=True,
plot_opts={}, **kwargs):
"""
Treat the passed plot as an base plot for abstract rendering, generate the
proper Bokeh plot based on the passed parameters.
This is a convenience for:
> src=source(plot, ...)
> <plot-type>(source=src, <params>, **ar.mapping(src))
Transfers plot title, width, height from the original plot
plot -- Plot to based new plot off of
remove_original -- Remove the source plot from the document (default: true)
plot_opts -- Options passed directly to soure.
This parameter only needs to be used if there is a name
conflict bewteen target plot type and
source options (see kwargs note)
**kwargs -- Arugments for the plot or source as needed.
If in conflict, a kwarg will be applied to the source function.
If this causes incorrecte behavior, the plot arguments may
be put in the plot_opts parameter instead.
returns -- A new plot
"""
# Remove the base plot (if requested)
if remove_original and plot in curdoc().context.children:
curdoc().context.children.remove(plot)
# Sift kwargs
source_opts = {}
for key in ServerDataSource().vm_props():
if key in kwargs:
source_opts[key] = kwargs.pop(key)
for name in get_function_code(source).co_varnames:
if name in kwargs:
source_opts[name] = kwargs.pop(name)
# Transfer specific items from the source plot, then updates from kwargs
plot_opts['plot_width'] = plot.plot_width
plot_opts['plot_height'] = plot.plot_height
plot_opts['title'] = plot.title
plot_opts.update(kwargs)
src = source(plot, agg, info, shader, **source_opts)
plot_opts.update(mapping(src))
if shader.out == "image":
new_plot = image(source=src, **plot_opts)
elif shader.out == "image_rgb":
new_plot = image_rgba(source=src, **plot_opts)
elif shader.out == "multi_line":
new_plot = multi_line(source=src, **plot_opts)
else:
raise ValueError("Unhandled output type %s" % shader.out)
return new_plot