本文整理汇总了Python中six.get_function_defaults函数的典型用法代码示例。如果您正苦于以下问题:Python get_function_defaults函数的具体用法?Python get_function_defaults怎么用?Python get_function_defaults使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_function_defaults函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: infrastructure
def infrastructure(
confirm=True,
color=colors.yellow,
autoconfirm_env_var='FABRICIO_INFRASTRUCTURE_AUTOCONFIRM',
):
def _decorator(task):
@functools.wraps(task)
def _task(*args, **kwargs):
if confirm:
confirmed = utils.yes(os.environ.get(autoconfirm_env_var, 0))
if not confirmed and not console.confirm(
'Are you sure you want to select {infrastructure} '
'infrastructure to run task(s) on?'.format(
infrastructure=color(task.__name__),
),
default=False,
):
fab.abort('Aborted')
fab.env.infrastructure = task.__name__
return task(*args, **kwargs)
return fab.task(_task)
fab.env.setdefault('infrastructure', None)
if callable(confirm):
func, confirm = confirm, six.get_function_defaults(infrastructure)[0]
return _decorator(func)
return _decorator
示例2: 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)
)
# 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)
示例3: 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
示例4: _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)
示例5: get_function_arguments
def get_function_arguments(func):
"""Return (args, kwargs) for func, excluding `self`"""
code = six.get_function_code(func)
defaults = six.get_function_defaults(func) or []
arg_names = [var for var in code.co_varnames[: code.co_argcount] if var != "self"]
n_required = len(arg_names) - len(defaults)
return arg_names[:n_required], arg_names[n_required:]
示例6: wrapped
def wrapped(cls, *args, **kwargs):
def is_mod_of_all(user, subreddit):
mod_subs = user.get_cached_moderated_reddits()
subs = six.text_type(subreddit).lower().split('+')
return all(sub in mod_subs for sub in subs)
if cls is None: # Occurs with (un)friend
assert login
raise errors.LoginRequired(function.__name__)
# This segment of code uses hasattr to determine what instance type
# the function was called on. We could use isinstance if we wanted
# to import the types at runtime (decorators is used by all the
# types).
if mod:
if hasattr(cls, 'reddit_session'):
# Defer access until necessary for RedditContentObject.
# This is because scoped sessions may not require this
# attribute to exist, thus it might not be set.
subreddit = cls if hasattr(cls, '_fast_name') else False
else:
subreddit = kwargs.get(
'subreddit', args[0] if args else None)
if subreddit is None: # Try the default value
defaults = six.get_function_defaults(function)
subreddit = defaults[0] if defaults else None
else:
subreddit = None
obj = getattr(cls, 'reddit_session', cls)
# This function sets _use_oauth for one time use only.
# Verify that statement is actually true.
assert not obj._use_oauth # pylint: disable=W0212
if scope and obj.has_scope(scope):
obj._use_oauth = True # pylint: disable=W0212
elif oauth_only:
raise errors.OAuthScopeRequired(function.__name__, scope)
elif login and obj.is_logged_in():
if subreddit is False:
# Now fetch the subreddit attribute. There is no good
# reason for it to not be set during a logged in session.
subreddit = cls.subreddit
if mod and not is_mod_of_all(obj.user, subreddit):
if scope:
raise errors.ModeratorOrScopeRequired(
function.__name__, scope)
raise errors.ModeratorRequired(function.__name__)
elif login:
if scope:
raise errors.LoginOrScopeRequired(function.__name__, scope)
raise errors.LoginRequired(function.__name__)
try:
return function(cls, *args, **kwargs)
finally:
obj._use_oauth = False # pylint: disable=W0212
示例7: _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
示例8: 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))
示例9: reset_defaults
def reset_defaults(function):
import six
from copy import deepcopy
defaults = six.get_function_defaults(function)
def decorator(*args, **kwargs):
if six.PY3: function.__defaults__ = deepcopy(defaults)
else: function.func_defaults = deepcopy(defaults)
return function(*args, **kwargs)
decorator.__name__ = function.__name__
decorator.__doc__ = function.__doc__
return decorator
示例10: save_function
def save_function(pickler, obj):
if not _locate_function(obj, pickler):
log.info("F1: %s" % obj)
globs = get_function_globals(obj)
mod_name = obj.__module__
pickler.save_reduce(_create_function, (get_function_code(obj),
{},
obj.__name__,
get_function_defaults(obj),
get_function_closure(obj),
obj.__dict__,
mod_name), obj=obj, func_globals=globs)
log.info("# F1 %s" % obj)
else:
log.info("F2: %s" % obj)
StockPickler.save_global(pickler, obj)
log.info("# F2 %s" % obj)
return
示例11: _fetch_argnames_argvalues
def _fetch_argnames_argvalues(method, args, kwargs):
# argnames = inspect.getargspec(method)[0]
nargs = six.get_function_code(method).co_argcount
names = six.get_function_code(method).co_varnames
argnames = list(names[:nargs])
if len(argnames) == 0:
return ([],[])
if len(argnames) == 1 and argnames[0] == 'self':
return ([],[])
if argnames[0] == 'self':
del argnames[0]
defaults = six.get_function_defaults(method)
if defaults is None:
defaults = []
argvalues = _map_args_kwargs_to_argvalues(args, kwargs, argnames, defaults)
return (argnames, argvalues)
示例12: test_get_function_defaults
def test_get_function_defaults():
def f(x, y=3, b=4):
pass
assert six.get_function_defaults(f) == (3, 4)
示例13: _compilecode
def _compilecode(function, name, impl, args, varargs, kwargs):
"""Get generated code.
:return: function proxy generated code.
:rtype: str
"""
newcodestr, generatedname, impl_name = _generatecode(
function=function, name=name, impl=impl,
args=args, varargs=varargs, kwargs=kwargs
)
try:
__file__ = getfile(function)
except TypeError:
__file__ = '<string>'
# compile newcodestr
code = compile(newcodestr, __file__, 'single')
# define the code with the new function
_globals = {}
exec_(code, _globals)
# get new code
_var = _globals[generatedname]
newco = get_function_code(_var)
# get new consts list
newconsts = list(newco.co_consts)
if PY3:
newcode = list(newco.co_code)
else:
newcode = [ord(co) for co in newco.co_code]
consts_values = {impl_name: impl}
# change LOAD_GLOBAL to LOAD_CONST
index = 0
newcodelen = len(newcode)
while index < newcodelen:
if newcode[index] == LOAD_GLOBAL:
oparg = newcode[index + 1] + (newcode[index + 2] << 8)
name = newco.co_names[oparg]
if name in consts_values:
const_value = consts_values[name]
if const_value in newconsts:
pos = newconsts.index(const_value)
else:
pos = len(newconsts)
newconsts.append(consts_values[name])
newcode[index] = LOAD_CONST
newcode[index + 1] = pos & 0xFF
newcode[index + 2] = pos >> 8
index += 1
codeobj = getcodeobj(newconsts, newcode, newco, get_function_code(function))
# instanciate a new function
if function is None or isbuiltin(function):
result = FunctionType(codeobj, {})
else:
result = type(function)(
codeobj,
get_function_globals(function),
function.__name__,
get_function_defaults(function),
get_function_closure(function)
)
return result
示例14: func_defaults
def func_defaults(self):
return six.get_function_defaults(self.bobo_original)
示例15: setUp
def setUp(self):
# http://effbot.org/zone/default-values.htm
six.get_function_defaults(do_tally)[0][:] = []
pass