當前位置: 首頁>>代碼示例>>Python>>正文


Python inspect.getcallargs方法代碼示例

本文整理匯總了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 
開發者ID:cherrypy,項目名稱:cherrypy,代碼行數:24,代碼來源:__init__.py

示例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) 
開發者ID:prkumar,項目名稱:uplink,代碼行數:21,代碼來源:utils.py

示例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)) 
開發者ID:hrhodin,項目名稱:UnsupervisedGeometryAwareRepresentationLearning,代碼行數:27,代碼來源:engine.py

示例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) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:20,代碼來源:edit.py

示例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)) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:27,代碼來源:__init__.py

示例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 
開發者ID:openstack,項目名稱:compute-hyperv,代碼行數:20,代碼來源:volumeops.py

示例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 
開發者ID:AirtestProject,項目名稱:Airtest,代碼行數:22,代碼來源:logwraper.py

示例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
# ================= 
開發者ID:asweigart,項目名稱:pyautogui,代碼行數:22,代碼來源:__init__.py

示例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 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:20,代碼來源:test_inspect.py

示例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)) 
開發者ID:leokarlin,項目名稱:LaSO,代碼行數:27,代碼來源:engine.py

示例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']) 
開發者ID:cloudify-cosmo,項目名稱:cloudify-cli,代碼行數:19,代碼來源:test_deployments.py

示例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']) 
開發者ID:cloudify-cosmo,項目名稱:cloudify-cli,代碼行數:19,代碼來源:test_deployments.py

示例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 
開發者ID:LEW21,項目名稱:pydbus,代碼行數:19,代碼來源:exitable.py

示例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 
開發者ID:openstack,項目名稱:rally-openstack,代碼行數:22,代碼來源:validators.py

示例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) 
開發者ID:PacktPublishing,項目名稱:Hands-On-Application-Development-with-PyCharm,代碼行數:25,代碼來源:__init__.py


注:本文中的inspect.getcallargs方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。