Python inspect.getcallargs() Examples

The following are 30 code examples of inspect.getcallargs(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module inspect , or try the search function .
Example #1
Source File: test_deployments.py    From cloudify-cli with Apache License 2.0 6 votes vote down vote up
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']) 
Example #2
Source File: utils.py    From uplink with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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)) 
Example #4
Source File: __init__.py    From opsbro with MIT License 6 votes vote down vote up
def is_closable_iterator(obj):
    
    # 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 
Example #5
Source File: edit.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #6
Source File: __init__.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
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)) 
Example #7
Source File: api.py    From statsnba-playbyplay with MIT License 6 votes vote down vote up
def Resource(resource_name):
    def real_dec(func):
        @functools.wraps(func)
        def fetch_resource(*args, **kwargs):
            called_args = inspect.getcallargs(func, *args, **kwargs)
            # We do not need `self` for building the params
            self = called_args.pop('self')
            url = self._BuildUrl('http://stats.nba.com/stats/',
                                    resource_name,
                                    called_args)
            resp = self._FetchUrl(url)
            resp_dict = resp.json()
            if self._transform_json:
                resp_dict = Api._TransformResponseDict(resp_dict)
            return resp_dict
        return fetch_resource
    return real_dec


# noinspection PyPep8Naming 
Example #8
Source File: edit.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
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) 
Example #9
Source File: engine.py    From UnsupervisedGeometryAwareRepresentationLearning with GNU General Public License v3.0 6 votes vote down vote up
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)) 
Example #10
Source File: api_base.py    From InplusTrader_Linux with MIT License 6 votes vote down vote up
def api_exc_patch(func):
    if isinstance(func, FunctionType):
        @wraps(func)
        def deco(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except RQInvalidArgument:
                raise
            except Exception as e:
                if isinstance(e, TypeError):
                    exc_info = sys.exc_info()
                    try:
                        ret = inspect.getcallargs(unwrapper(func), *args, **kwargs)
                    except TypeError:
                        t, v, tb = exc_info
                        raise patch_user_exc(v.with_traceback(tb))

                if getattr(e, EXC_EXT_NAME, EXC_TYPE.NOTSET) == EXC_TYPE.NOTSET:
                    patch_system_exc(e)

                raise

        return deco
    return func 
Example #11
Source File: api_base.py    From InplusTrader_Linux with MIT License 6 votes vote down vote up
def api_exc_patch(func):
    if isinstance(func, FunctionType):
        @wraps(func)
        def deco(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except RQInvalidArgument:
                raise
            except Exception as e:
                if isinstance(e, TypeError):
                    exc_info = sys.exc_info()
                    try:
                        ret = inspect.getcallargs(unwrapper(func), *args, **kwargs)
                    except TypeError:
                        t, v, tb = exc_info
                        raise patch_user_exc(v.with_traceback(tb))

                if getattr(e, EXC_EXT_NAME, EXC_TYPE.NOTSET) == EXC_TYPE.NOTSET:
                    patch_system_exc(e)

                raise

        return deco
    return func 
Example #12
Source File: argtools.py    From petridishnn with MIT License 6 votes vote down vote up
def map_arg(**maps):
    """
    Apply a mapping on certain argument before calling the original function.

    Args:
        maps (dict): {argument_name: map_func}
    """
    def deco(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            if six.PY2:
                argmap = inspect.getcallargs(func, *args, **kwargs)
            else:
                # getcallargs was deprecated since 3.5
                sig = inspect.signature(func)
                argmap = sig.bind_partial(*args, **kwargs).arguments
            for k, map_func in six.iteritems(maps):
                if k in argmap:
                    argmap[k] = map_func(argmap[k])
            return func(**argmap)
        return wrapper
    return deco 
Example #13
Source File: volumeops.py    From compute-hyperv with Apache License 2.0 6 votes vote down vote up
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 
Example #14
Source File: __init__.py    From Dindo-Bot with MIT License 6 votes vote down vote up
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
# ================= 
Example #15
Source File: __init__.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example #16
Source File: test_deployments.py    From cloudify-cli with Apache License 2.0 6 votes vote down vote up
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']) 
Example #17
Source File: engine.py    From LaSO with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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)) 
Example #18
Source File: exitable.py    From pydbus with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 
Example #19
Source File: validators.py    From rally-openstack with Apache License 2.0 6 votes vote down vote up
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 
Example #20
Source File: test_inspect.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #21
Source File: test_inspect.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
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 
Example #22
Source File: __init__.py    From pyautogui with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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
# ================= 
Example #23
Source File: __init__.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
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) 
Example #24
Source File: metaclasses.py    From pymtl with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __call__( self, *args, **kwargs ):
    """Called whenever a class instance is created, allowing us to
    capture all the arguments and argument values passed to the class.
    These arguments are stored as an OrderedDict in the _args field of
    the instance so they can be used later.
    """

    # Get the constructor prototype

    call_spec = inspect.getargspec( self.__init__ )
    inst = super( MetaCollectArgs, self ).__call__( *args, **kwargs )
    inst._args = inspect.getcallargs( inst.__init__, *args, **kwargs )
    for key in inst._args.keys():
      # delete the self argument
      if inst._args[ key ] == inst:
        del inst._args[ key ]

    # Return the instance

    return inst 
Example #25
Source File: logwraper.py    From Airtest with Apache License 2.0 6 votes vote down vote up
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 
Example #26
Source File: test_inspect.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def assertEqualCallArgs(self, func, call_params_string, locs=None):
        locs = dict(locs or {}, func=func)
        r1 = eval('func(%s)' % call_params_string, None, locs)
        r2 = eval('inspect.getcallargs(func, %s)' % call_params_string, None,
                  locs)
        self.assertEqual(r1, r2) 
Example #27
Source File: test_plugins.py    From cloudify-cli with Apache License 2.0 5 votes vote down vote up
def test_update_force_flag_is_true(self):
        update_client_mock = Mock()
        self.client.plugins_update.update_plugins = update_client_mock
        self.invoke('cfy plugins update asdf --force')

        calls = update_client_mock.mock_calls
        self.assertEqual(len(calls), 1)
        _, args, kwargs = calls[0]
        call_args = inspect.getcallargs(
            plugins_update.PluginsUpdateClient(None).update_plugins,
            *args, **kwargs)

        self.assertIn('force', call_args)
        self.assertTrue(call_args['force']) 
Example #28
Source File: test_inspect.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def assertEqualCallArgs(self, func, call_params_string, locs=None):
        locs = dict(locs or {}, func=func)
        r1 = eval('func(%s)' % call_params_string, None, locs)
        r2 = eval('inspect.getcallargs(func, %s)' % call_params_string, None,
                  locs)
        self.assertEqual(r1, r2) 
Example #29
Source File: test_plugins.py    From cloudify-cli with Apache License 2.0 5 votes vote down vote up
def test_update_force_flag_is_false(self):
        update_client_mock = Mock()
        self.client.plugins_update.update_plugins = update_client_mock
        self.invoke('cfy plugins update asdf')

        calls = update_client_mock.mock_calls
        self.assertEqual(len(calls), 1)
        _, args, kwargs = calls[0]
        call_args = inspect.getcallargs(
            plugins_update.PluginsUpdateClient(None).update_plugins,
            *args, **kwargs)

        self.assertIn('force', call_args)
        self.assertFalse(call_args['force']) 
Example #30
Source File: arg_checker.py    From InplusTrader_Linux with MIT License 5 votes vote down vote up
def apply_rules(*rules):
    def decorator(func):
        @wraps(func)
        def api_rule_check_wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except RQInvalidArgument:
                raise
            except Exception:
                exc_info = sys.exc_info()
                t, v, tb = exc_info

                try:
                    call_args = inspect.getcallargs(unwrapper(func), *args, **kwargs)
                except TypeError as e:
                    six.reraise(RQTypeError, RQTypeError(*e.args), tb)
                    return

                try:
                    for r in rules:
                        r.verify(func.__name__, call_args[r.arg_name])
                except RQInvalidArgument as e:
                    six.reraise(RQInvalidArgument, e, tb)
                    return

                raise

        api_rule_check_wrapper._rq_exception_checked = True
        return api_rule_check_wrapper

    return decorator