Python inspect.getargspec() Examples
The following are 30
code examples of inspect.getargspec().
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: script.py From jbox with MIT License | 6 votes |
def analyse_action(func): """Analyse a function.""" description = inspect.getdoc(func) or 'undocumented action' arguments = [] args, varargs, kwargs, defaults = inspect.getargspec(func) if varargs or kwargs: raise TypeError('variable length arguments for action not allowed.') if len(args) != len(defaults or ()): raise TypeError('not all arguments have proper definitions') for idx, (arg, definition) in enumerate(zip(args, defaults or ())): if arg.startswith('_'): raise TypeError('arguments may not start with an underscore') if not isinstance(definition, tuple): shortcut = None default = definition else: shortcut, default = definition argument_type = argument_types[type(default)] if isinstance(default, bool) and default is True: arg = 'no-' + arg arguments.append((arg.replace('_', '-'), shortcut, default, argument_type)) return func, description, arguments
Example #2
Source File: metadata_wrapper_test.py From cassandra-dtest with Apache License 2.0 | 6 votes |
def _each_subclass_instantiated_with_mock_args(self): """ This returns an instantiated copy of each subclass of UpdatingMetadataWrapperBase, passing a MagicMock for each argument on initialization. This lets us test properties that should hold for all subclasses. I don't like having tests depend on this weird metaprogramming, but I'd rather have this, which generates tests for any future subclasses, than miss tests for them. """ for klaus in UpdatingMetadataWrapperBase.__subclasses__(): # get length of argument list for class init init_arg_len = len(inspect.getargspec(klaus.__init__)[0]) # args list is one shorter -- argspec includes self init_args = [MagicMock() for _ in range(init_arg_len - 1)] yield klaus(*init_args)
Example #3
Source File: dev_appserver.py From browserscope with Apache License 2.0 | 6 votes |
def ModuleHasValidMainFunction(module): """Determines if a module has a main function that takes no arguments. This includes functions that have arguments with defaults that are all assigned, thus requiring no additional arguments in order to be called. Args: module: A types.ModuleType instance. Returns: True if the module has a valid, reusable main function; False otherwise. """ if hasattr(module, 'main') and type(module.main) is types.FunctionType: arg_names, var_args, var_kwargs, default_values = inspect.getargspec( module.main) if len(arg_names) == 0: return True if default_values is not None and len(arg_names) == len(default_values): return True return False
Example #4
Source File: langhelpers.py From jbox with MIT License | 6 votes |
def getargspec_init(method): """inspect.getargspec with considerations for typical __init__ methods Wraps inspect.getargspec with error handling for typical __init__ cases:: object.__init__ -> (self) other unreflectable (usually C) -> (self, *args, **kwargs) """ try: return compat.inspect_getargspec(method) except TypeError: if method is object.__init__: return (['self'], None, None, None) else: return (['self'], 'args', 'kwargs', None)
Example #5
Source File: registry.py From fine-lm with MIT License | 6 votes |
def register_ranged_hparams(name=None): """Register a RangedHParams set. name defaults to fn name snake-cased.""" def decorator(rhp_fn, registration_name=None): """Registers & returns hp_fn with registration_name or default name.""" rhp_name = registration_name or default_name(rhp_fn) if rhp_name in _RANGED_HPARAMS: raise LookupError("RangedHParams set %s already registered." % rhp_name) # Check that the fn takes a single argument args, varargs, keywords, _ = inspect.getargspec(rhp_fn) if len(args) != 1 or varargs is not None or keywords is not None: raise ValueError("RangedHParams set function must take a single " "argument, the RangedHParams object.") _RANGED_HPARAMS[rhp_name] = rhp_fn return rhp_fn # Handle if decorator was used without parens if callable(name): rhp_fn = name return decorator(rhp_fn, registration_name=default_name(rhp_fn)) return lambda rhp_fn: decorator(rhp_fn, name)
Example #6
Source File: engine.py From UnsupervisedGeometryAwareRepresentationLearning with GNU General Public License v3.0 | 6 votes |
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 #7
Source File: base.py From StormOnline with Apache License 2.0 | 6 votes |
def filter_chain(filters, token, func, *args, **kwargs): if token == -1: return func() else: def _inner_method(): fm = filters[token] fargs = getargspec(fm)[0] if len(fargs) == 1: # Only self arg result = func() if result is None: return fm() else: raise IncorrectPluginArg(u'Plugin filter method need a arg to receive parent method result.') else: return fm(func if fargs[1] == '__' else func(), *args, **kwargs) return filter_chain(filters, token - 1, _inner_method, *args, **kwargs)
Example #8
Source File: pyscf_helpers.py From pyscf with Apache License 2.0 | 6 votes |
def oneshot(equations, *args): """ A one-shot calculation. Args: equations (callable): coupled-cluster equations; args (iterable): amplitudes and hamiltonian matrix elements as dicts; Returns: Results of the calculation. """ input_args = inspect.getargspec(equations).args fw_args = {} for i in args: fw_args.update(i) # Remove excess arguments from the Hamiltonian fw_args = {k: v for k, v in fw_args.items() if k in input_args} # Check missing arguments missing = set(input_args) - set(fw_args.keys()) if len(missing) > 0: raise ValueError("Following arguments are missing: {}".format(', '.join(missing))) return equations(**fw_args)
Example #9
Source File: test_docstrings.py From collectd-haproxy with MIT License | 6 votes |
def assert_docstring_includes_param_metadata(thing, path): if inspect.isclass(thing): return docstring = inspect.getdoc(thing) if not docstring: return for arg_name in inspect.getargspec(thing).args: if arg_name in ("self", "cls"): continue if ":param %s:" % arg_name not in docstring: raise AssertionError( "Missing :param: for arg %s of %s" % (arg_name, path) ) if ":type %s:" % arg_name not in docstring: raise AssertionError( "Missing :type: for arg %s of %s" % (arg_name, path) )
Example #10
Source File: ccdc.py From yatsm with MIT License | 6 votes |
def version_kwargs(d): """ Fix API calls for kwargs dict ``d`` that should have key ``estimator`` """ argspec = inspect.getargspec(CCDCesque.__init__) if 'estimator' in argspec.args: # Spec updated to estimator={object': ..., 'fit': {}} idx = [i for i, arg in enumerate(argspec.args) if arg == 'estimator'][0] - 1 if isinstance(argspec.defaults[idx], dict): return d else: d['estimator'] = {'object': d['estimator'], 'fit': {}} elif 'lm' in argspec.args: new_key, old_key = 'lm', 'estimator' d[new_key] = d.pop(old_key) return d else: raise KeyError('Neither "lm" nor "estimator" are keys in ' 'CCDCesque.__init__')
Example #11
Source File: checker.py From django-healthchecks with MIT License | 6 votes |
def _get_check_functions(name=None, request=None): checks = _get_registered_health_checks() if not checks or (name and name not in checks): raise StopIteration() checks = _filter_checks_on_permission(request, checks) if not checks or (name and name not in checks): raise PermissionDenied() for service, func_string in checks.items(): if name and name != service: continue if callable(func_string): check_func = func_string elif func_string.startswith(('https://', 'http://')): check_func = _http_healthcheck_func(func_string) else: check_func = import_string(func_string) spec = inspect.getargspec(check_func) if spec.args == ['request']: check_func = functools.partial(check_func, request) yield service, check_func
Example #12
Source File: methods.py From Jtyoui with MIT License | 6 votes |
def get_argCount(func) -> int: """获取函数对象的参数个数 def sum(a,b): return(a+b) print(sum.__code__.co_argcount) # 2 #输出的函数参数个数 print(sum.__code__.co_varnames) # ('a', 'b') #这里会输出函数用到的所有变量名,不只是参数名 print(sum.__defaults__) # None # 返回参数的初始值 import inspect inspect.getargspec(sum) #ArgSpec(args=['a', 'b'], varargs=None, keywords=None, defaults=None) :param func: 函数对象 :return: 函数对象的参数个数 """ return func.__code__.co_argcount
Example #13
Source File: __init__.py From LGWebOSRemote with MIT License | 6 votes |
def usage(error=None): if error: print ("Error: " + error) print ("LGTV Controller") print ("Author: Karl Lattimer <karl@qdh.org.uk>") print ("Usage: lgtv <command> [parameter]\n") print ("Available Commands:") print (" -i interactive mode") print (" scan") print (" auth <host> <tv_name>") commands = LGTVRemote.getCommands() for c in commands: args = getargspec(LGTVRemote.__dict__[c]) if len(args.args) > 1: a = ' <' + '> <'.join(args.args[1:-1]) + '>' print (' <tv_name> ' + c + a) else: print (' <tv_name> ' + c)
Example #14
Source File: __init__.py From LGWebOSRemote with MIT License | 6 votes |
def parseargs(command, argv): args = getargspec(LGTVRemote.__dict__[command]) args = args.args[1:-1] if len(args) != len(argv): raise Exception("Argument lengths do not match") output = {} for (i, a) in enumerate(args): if argv[i].lower() == "true": argv[i] = True elif argv[i].lower() == "false": argv[i] = False try: f = int(argv[i]) argv[i] = f except: try: f = float(argv[i]) argv[i] = f except: pass output[a] = argv[i] return output
Example #15
Source File: main.py From LGWebOSRemote with MIT License | 6 votes |
def usage(error=None): if error: print ("Error: " + error) print ("LGTV Controller") print ("Author: Karl Lattimer <karl@qdh.org.uk>") print ("Usage: lgtv <command> [parameter]\n") print ("Available Commands:") print (" scan") print (" auth Hostname/IP Authenticate and exit, creates initial config ~/.lgtv.json") for c in getCommands(LGTVClient): print (" " + c, end=" ") print (" " * (20 - len(c)), end=" ") args = getargspec(LGTVClient.__dict__[c]) print (' '.join(args.args[1:-1]))
Example #16
Source File: utils.py From zun with Apache License 2.0 | 6 votes |
def expects_func_args(*args): def _decorator_checker(dec): @functools.wraps(dec) def _decorator(f): base_f = get_wrapped_function(f) argspec = getargspec(base_f) if argspec[1] or argspec[2] or set(args) <= set(argspec[0]): # NOTE (ndipanov): We can't really tell if correct stuff will # be passed if it's a function with *args or **kwargs so # we still carry on and hope for the best return dec(f) else: raise TypeError("Decorated function %(f_name)s does not " "have the arguments expected by the " "decorator %(d_name)s" % {'f_name': base_f.__name__, 'd_name': dec.__name__}) return _decorator return _decorator_checker
Example #17
Source File: __init__.py From recruit with Apache License 2.0 | 5 votes |
def signature(f): return inspect.getargspec(f)
Example #18
Source File: mox.py From browserscope with Apache License 2.0 | 5 votes |
def __init__(self, method): """Creates a checker. Args: # method: A method to check. method: function Raises: ValueError: method could not be inspected, so checks aren't possible. Some methods and functions like built-ins can't be inspected. """ try: self._args, varargs, varkw, defaults = inspect.getargspec(method) except TypeError: raise ValueError('Could not get argument specification for %r' % (method,)) if inspect.ismethod(method): self._args = self._args[1:] # Skip 'self'. self._method = method self._has_varargs = varargs is not None self._has_varkw = varkw is not None if defaults is None: self._required_args = self._args self._default_args = [] else: self._required_args = self._args[:-len(defaults)] self._default_args = self._args[-len(defaults):]
Example #19
Source File: run_pylint.py From maintainer-quality-tools with GNU Affero General Public License v3.0 | 5 votes |
def run_pylint(paths, cfg, beta_msgs=None, sys_paths=None, extra_params=None): """Execute pylint command from original python library :param paths: List of paths of python modules to check with pylint :param cfg: String name of pylint configuration file :param sys_paths: List of paths to append to sys path :param extra_params: List of extra parameters to append in pylint command :return: Dict with python linter stats """ if sys_paths is None: sys_paths = [] if extra_params is None: extra_params = [] sys.path.extend(sys_paths) cmd = ['--rcfile=' + cfg] cmd.extend(extra_params) subpaths = get_subpaths(paths) if not subpaths: raise UserWarning("Python modules not found in paths %s" % (paths)) exclude = os.environ.get('EXCLUDE', '').split(',') subpaths = [path for path in subpaths if os.path.basename(path) not in exclude] if not subpaths: return {'error': 0} cmd.extend(subpaths) if 'do_exit' in inspect.getargspec(pylint.lint.Run.__init__)[0]: # pylint has renamed this keyword argument pylint_res = pylint.lint.Run(cmd, do_exit=False) else: pylint_res = pylint.lint.Run(cmd, exit=False) return pylint_res.linter.stats
Example #20
Source File: property_invoker.py From recipes-py with Apache License 2.0 | 5 votes |
def invoke_with_properties(callable_obj, all_props, environ, prop_defs, **additional_args): """ Invokes callable with filtered, type-checked properties. Args: callable_obj: The function to call, or class to instantiate. This supports passing in either RunSteps, or a recipe module, which is a class. all_props: A dictionary containing all the properties (strings) currently defined in the system. environ: A dictionary with environment to use for resolving 'from_environ' properties (usually os.environ, but replaced in tests). prop_defs: A dictionary of property name to property definitions (BoundProperty) for this callable. additional_args: kwargs to pass through to the callable. Note that the names of the arguments can correspond to positional arguments as well. Returns: The result of calling callable with the filtered properties and additional arguments. """ # To detect when they didn't specify a property that they have as a # function argument, list the arguments, through inspection, # and then comparing this list to the provided properties. We use a list # instead of a dict because getargspec returns a list which we would have to # convert to a dictionary, and the benefit of the dictionary is pretty small. if inspect.isclass(callable_obj): arg_names = inspect.getargspec(callable_obj.__init__).args arg_names.pop(0) # 'self' else: arg_names = inspect.getargspec(callable_obj).args return _invoke_with_properties(callable_obj, all_props, environ, prop_defs, arg_names, **additional_args)
Example #21
Source File: langhelpers.py From jbox with MIT License | 5 votes |
def get_func_kwargs(func): """Return the set of legal kwargs for the given `func`. Uses getargspec so is safe to call for methods, functions, etc. """ return compat.inspect_getargspec(func)[0]
Example #22
Source File: compat.py From jbox with MIT License | 5 votes |
def inspect_getargspec(func): return ArgSpec( *inspect_getfullargspec(func)[0:4] )
Example #23
Source File: decorator.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def getfullargspec(f): "A quick and dirty replacement for getfullargspec for Python 2.X" return FullArgSpec._make(inspect.getargspec(f) + ([], None, {}))
Example #24
Source File: metaclass_test.py From custom_inherit with MIT License | 5 votes |
def test_sideeffect2(): assert getdoc(Kid2.kid_method) == "kid" assert signature(Kid2.method) == signature(Parent.method)
Example #25
Source File: net_utils.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def check_css_params(**validators): '''A decorator for validating arguments for function with specified validating function which returns True or False. :param validators: argument and it's validation function :raises ValueError: If validation fails. ''' def decorator(f): @wraps(f) def wrapper(*args, **kwargs): arg_spec = inspect.getargspec(f) actual_args = dict(list(zip(arg_spec.args, args)) + list(kwargs.items())) dfs = arg_spec.defaults optional = dict(list(zip(arg_spec.args[-len(dfs):], dfs))) if dfs else {} for arg, func in list(validators.items()): if arg not in actual_args: continue value = actual_args[arg] if arg in optional and optional[arg] == value: continue if not func(value): raise ValueError( 'Illegal argument: {}={}'.format(arg, value)) return f(*args, **kwargs) return wrapper return decorator
Example #26
Source File: union.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def _valid_init_args(type_): args = set() for cls in type_.__mro__: args.update(inspect.getargspec(cls.__init__).args[1:]) if cls is BaseType: break return args
Example #27
Source File: decorator.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def getfullargspec(f): "A quick and dirty replacement for getfullargspec for Python 2.X" return FullArgSpec._make(inspect.getargspec(f) + ([], None, {}))
Example #28
Source File: net_utils.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def check_css_params(**validators): '''A decorator for validating arguments for function with specified validating function which returns True or False. :param validators: argument and it's validation function :raises ValueError: If validation fails. ''' def decorator(f): @wraps(f) def wrapper(*args, **kwargs): arg_spec = inspect.getargspec(f) actual_args = dict(list(zip(arg_spec.args, args)) + list(kwargs.items())) dfs = arg_spec.defaults optional = dict(list(zip(arg_spec.args[-len(dfs):], dfs))) if dfs else {} for arg, func in list(validators.items()): if arg not in actual_args: continue value = actual_args[arg] if arg in optional and optional[arg] == value: continue if not func(value): raise ValueError( 'Illegal argument: {}={}'.format(arg, value)) return f(*args, **kwargs) return wrapper return decorator
Example #29
Source File: validate.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def prepare_validator(func, argcount): if isinstance(func, classmethod): func = func.__get__(object).__func__ if len(inspect.getargspec(func).args) < argcount: @functools.wraps(func) def newfunc(*args, **kwargs): if not kwargs or kwargs.pop('context', 0) is 0: args = args[:-1] return func(*args, **kwargs) return newfunc return func
Example #30
Source File: union.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def _valid_init_args(type_): args = set() for cls in type_.__mro__: args.update(inspect.getargspec(cls.__init__).args[1:]) if cls is BaseType: break return args