本文整理汇总了Python中inspect.getcallargs方法的典型用法代码示例。如果您正苦于以下问题:Python inspect.getcallargs方法的具体用法?Python inspect.getcallargs怎么用?Python inspect.getcallargs使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类inspect
的用法示例。
在下文中一共展示了inspect.getcallargs方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: is_closable_iterator
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getcallargs [as 别名]
def is_closable_iterator(obj):
"""Detect if the given object is both closable and iterator."""
# Not an iterator.
if not is_iterator(obj):
return False
# A generator - the easiest thing to deal with.
import inspect
if inspect.isgenerator(obj):
return True
# A custom iterator. Look for a close method...
if not (hasattr(obj, 'close') and callable(obj.close)):
return False
# ... which doesn't require any arguments.
try:
inspect.getcallargs(obj.close)
except TypeError:
return False
else:
return True
示例2: get_call_args
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getcallargs [as 别名]
def get_call_args(f, *args, **kwargs):
sig = signature(f)
arguments = sig.bind(*args, **kwargs).arguments
# apply defaults:
new_arguments = []
for name, param in sig.parameters.items():
try:
new_arguments.append((name, arguments[name]))
except KeyError:
if param.default is not param.empty:
val = param.default
elif param.kind is param.VAR_POSITIONAL:
val = ()
elif param.kind is param.VAR_KEYWORD:
val = {}
else:
continue
new_arguments.append((name, val))
return collections.OrderedDict(new_arguments)
示例3: _check_signature
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getcallargs [as 别名]
def _check_signature(self, fn, fn_description, *args, **kwargs):
exception_msg = None
if IS_PYTHON2:
try:
callable_ = fn if hasattr(fn, '__name__') else fn.__call__
inspect.getcallargs(callable_, self, *args, **kwargs)
except TypeError as exc:
spec = inspect.getargspec(callable_)
fn_params = list(spec.args)
exception_msg = str(exc)
else:
signature = inspect.signature(fn)
try:
signature.bind(self, *args, **kwargs)
except TypeError as exc:
fn_params = list(signature.parameters)
exception_msg = str(exc)
if exception_msg:
passed_params = [self] + list(args) + list(kwargs)
raise ValueError("Error adding {} '{}': "
"takes parameters {} but will be called with {} "
"({})".format(
fn, fn_description, fn_params, passed_params, exception_msg))
示例4: __new__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getcallargs [as 别名]
def __new__(cls, name, bases, attrs):
get_form = attrs.get('get_form')
if get_form and inspect.isfunction(get_form):
try:
inspect.getcallargs(get_form, None)
except TypeError:
warnings.warn(
"`%s.%s.get_form` method must define a default value for "
"its `form_class` argument." % (attrs['__module__'], name),
RemovedInDjango110Warning, stacklevel=2
)
def get_form_with_form_class(self, form_class=None):
if form_class is None:
form_class = self.get_form_class()
return get_form(self, form_class=form_class)
attrs['get_form'] = get_form_with_form_class
return super(FormMixinBase, cls).__new__(cls, name, bases, attrs)
示例5: authenticate
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getcallargs [as 别名]
def authenticate(**credentials):
"""
If the given credentials are valid, return a User object.
"""
for backend, backend_path in _get_backends(return_tuples=True):
try:
inspect.getcallargs(backend.authenticate, **credentials)
except TypeError:
# This backend doesn't accept these credentials as arguments. Try the next one.
continue
try:
user = backend.authenticate(**credentials)
except PermissionDenied:
# This backend says to stop in our tracks - this user should not be allowed in at all.
return None
if user is None:
continue
# Annotate the user object with the path of the backend.
user.backend = backend_path
return user
# The credentials supplied are invalid to all backends, fire signal
user_login_failed.send(sender=__name__,
credentials=_clean_credentials(credentials))
示例6: volume_snapshot_lock
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getcallargs [as 别名]
def volume_snapshot_lock(f):
"""Synchronizes volume snapshot related operations.
The locks will be applied on a per-instance basis. The decorated method
must accept an instance object.
"""
def inner(*args, **kwargs):
all_args = inspect.getcallargs(f, *args, **kwargs)
instance = all_args['instance']
lock_name = "volume-snapshot-%s" % instance.name
@utils.synchronized(lock_name)
def synchronized():
return f(*args, **kwargs)
return synchronized()
return inner
示例7: Logwrap
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getcallargs [as 别名]
def Logwrap(f, logger):
@functools.wraps(f)
def wrapper(*args, **kwargs):
start = time.time()
m = inspect.getcallargs(f, *args, **kwargs)
fndata = {'name': f.__name__, 'call_args': m, 'start_time': start}
logger.running_stack.append(fndata)
try:
res = f(*args, **kwargs)
except Exception as e:
data = {"traceback": traceback.format_exc(), "end_time": time.time()}
fndata.update(data)
raise
else:
fndata.update({'ret': res, "end_time": time.time()})
finally:
logger.log('function', fndata)
logger.running_stack.pop()
return res
return wrapper
示例8: _genericPyAutoGUIChecks
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getcallargs [as 别名]
def _genericPyAutoGUIChecks(wrappedFunction):
"""
A decorator that calls failSafeCheck() before the decorated function and
_handlePause() after it.
"""
@functools.wraps(wrappedFunction)
def wrapper(*args, **kwargs):
funcArgs = inspect.getcallargs(wrappedFunction, *args, **kwargs)
failSafeCheck()
returnVal = wrappedFunction(*args, **kwargs)
_handlePause(funcArgs.get("_pause"))
return returnVal
return wrapper
# General Functions
# =================
示例9: assertEqualException
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getcallargs [as 别名]
def assertEqualException(self, func, call_param_string, locs=None):
locs = dict(locs or {}, func=func)
try:
eval('func(%s)' % call_param_string, None, locs)
except Exception as e:
ex1 = e
else:
self.fail('Exception not raised')
try:
eval('inspect.getcallargs(func, %s)' % call_param_string, None,
locs)
except Exception as e:
ex2 = e
else:
self.fail('Exception not raised')
self.assertIs(type(ex1), type(ex2))
self.assertEqual(str(ex1), str(ex2))
del ex1, ex2
示例10: _check_signature
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getcallargs [as 别名]
def _check_signature(self, fn, fn_description, *args, **kwargs):
exception_msg = None
if IS_PYTHON2:
try:
callable_ = fn if hasattr(fn, '__name__') else fn.__call__
inspect.getcallargs(callable_, self, *args, **kwargs)
except TypeError as exc:
spec = inspect.getargspec(callable_)
fn_params = list(spec.args)
exception_msg = str(exc)
else:
signature = inspect.signature(fn)
try:
signature.bind(self, *args, **kwargs)
except TypeError as exc:
fn_params = list(signature.parameters)
exception_msg = str(exc)
if exception_msg:
passed_params = [self] + list(args) + list(kwargs)
raise ValueError("Error adding {} '{}': "
"takes parameters {} but will be called with {} "
"({}).".format(
fn, fn_description, fn_params, passed_params, exception_msg))
示例11: test_deployment_update_update_plugins_is_false
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getcallargs [as 别名]
def test_deployment_update_update_plugins_is_false(self):
update_client_mock = Mock()
self.client.deployment_updates.update_with_existing_blueprint = \
update_client_mock
self.invoke('deployments update dep-1 -b b2 --dont-update-plugins')
calls = self.client.deployment_updates\
.update_with_existing_blueprint.mock_calls
self.assertEqual(len(calls), 1)
_, args, kwargs = calls[0]
call_args = inspect.getcallargs(
deployment_updates.DeploymentUpdatesClient(None)
.update_with_existing_blueprint,
*args, **kwargs)
self.assertIn('update_plugins', call_args)
self.assertFalse(call_args['update_plugins'])
示例12: test_deployment_update_update_plugins_is_true
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getcallargs [as 别名]
def test_deployment_update_update_plugins_is_true(self):
update_client_mock = Mock()
self.client.deployment_updates.update_with_existing_blueprint = \
update_client_mock
self.invoke('deployments update dep-1 -b b2')
calls = self.client.deployment_updates\
.update_with_existing_blueprint.mock_calls
self.assertEqual(len(calls), 1)
_, args, kwargs = calls[0]
call_args = inspect.getcallargs(
deployment_updates.DeploymentUpdatesClient(None)
.update_with_existing_blueprint,
*args, **kwargs)
self.assertIn('update_plugins', call_args)
self.assertTrue(call_args['update_plugins'])
示例13: __exit__
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getcallargs [as 别名]
def __exit__(self, exc_type = None, exc_value = None, traceback = None):
if self._exited:
return
for cb in reversed(self._at_exit_cbs):
call_with_exc = True
try:
inspect.getcallargs(cb, exc_type, exc_value, traceback)
except TypeError:
call_with_exc = False
if call_with_exc:
cb(exc_type, exc_value, traceback)
else:
cb()
self._at_exit_cbs = None
示例14: with_roles_ctx
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getcallargs [as 别名]
def with_roles_ctx():
"""Add roles to users for validate
"""
def decorator(func):
def wrapper(*args, **kw):
func_type = inspect.getcallargs(func, *args, **kw)
config = func_type.get("config", {})
context = func_type.get("context", {})
if config.get("contexts", {}).get("roles") \
and context.get("admin", {}):
context["config"] = config["contexts"]
rolegenerator = roles.RoleGenerator(context)
with rolegenerator:
rolegenerator.setup()
func(*args, **kw)
else:
func(*args, **kw)
return wrapper
return decorator
示例15: authenticate
# 需要导入模块: import inspect [as 别名]
# 或者: from inspect import getcallargs [as 别名]
def authenticate(request=None, **credentials):
"""
If the given credentials are valid, return a User object.
"""
for backend, backend_path in _get_backends(return_tuples=True):
try:
inspect.getcallargs(backend.authenticate, request, **credentials)
except TypeError:
# This backend doesn't accept these credentials as arguments. Try the next one.
continue
try:
user = backend.authenticate(request, **credentials)
except PermissionDenied:
# This backend says to stop in our tracks - this user should not be allowed in at all.
break
if user is None:
continue
# Annotate the user object with the path of the backend.
user.backend = backend_path
return user
# The credentials supplied are invalid to all backends, fire signal
user_login_failed.send(sender=__name__, credentials=_clean_credentials(credentials), request=request)