Python inspect.getargs() Examples
The following are 30
code examples of inspect.getargs().
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: dochelpers.py From spyder-kernels with MIT License | 6 votes |
def getargtxt(obj, one_arg_per_line=True): """ Get the names and default values of a function's arguments Return list with separators (', ') formatted for calltips """ args = getargs(obj) if args: sep = ', ' textlist = None for i_arg, arg in enumerate(args): if textlist is None: textlist = [''] textlist[-1] += arg if i_arg < len(args)-1: textlist[-1] += sep if len(textlist[-1]) >= 32 or one_arg_per_line: textlist.append('') if inspect.isclass(obj) or inspect.ismethod(obj): if len(textlist) == 1: return None if 'self'+sep in textlist: textlist.remove('self'+sep) return textlist
Example #2
Source File: test_decorators.py From Computable with MIT License | 6 votes |
def getargspec(obj): """Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. Modified version of inspect.getargspec from the Python Standard Library.""" if inspect.isfunction(obj): func_obj = obj elif inspect.ismethod(obj): func_obj = obj.im_func else: raise TypeError('arg is not a Python function') args, varargs, varkw = inspect.getargs(func_obj.func_code) return args, varargs, varkw, func_obj.func_defaults #----------------------------------------------------------------------------- # Testing functions
Example #3
Source File: oinspect.py From Computable with MIT License | 6 votes |
def getargspec(obj): """Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. Modified version of inspect.getargspec from the Python Standard Library.""" if inspect.isfunction(obj): func_obj = obj elif inspect.ismethod(obj): func_obj = obj.im_func elif hasattr(obj, '__call__'): func_obj = obj.__call__ else: raise TypeError('arg is not a Python function') args, varargs, varkw = inspect.getargs(func_obj.func_code) return args, varargs, varkw, func_obj.func_defaults
Example #4
Source File: utils.py From pipenv with MIT License | 6 votes |
def get_method_args(target_method): # type: (Callable) -> Tuple[Callable, Optional[inspect.Arguments]] """ Returns the arguments for a callable. :param Callable target_method: A callable to retrieve arguments for :return: A 2-tuple of the original callable and its resulting arguments :rtype: Tuple[Callable, Optional[inspect.Arguments]] """ inspected_args = None try: inspected_args = inspect.getargs(target_method.__code__) except AttributeError: target_func = getattr(target_method, "__func__", None) if target_func is not None: inspected_args = inspect.getargs(target_func.__code__) else: target_func = target_method return target_func, inspected_args
Example #5
Source File: inspection.py From qcore with Apache License 2.0 | 6 votes |
def getargspec(func): """Variation of inspect.getargspec that works for more functions. This function works for Cythonized, non-cpdef functions, which expose argspec information but are not accepted by getargspec. It also works for Python 3 functions that use annotations, which are simply ignored. However, keyword-only arguments are not supported. """ if inspect.ismethod(func): func = func.__func__ # Cythonized functions have a .__code__, but don't pass inspect.isfunction() try: code = func.__code__ except AttributeError: raise TypeError("{!r} is not a Python function".format(func)) if hasattr(code, "co_kwonlyargcount") and code.co_kwonlyargcount > 0: raise ValueError("keyword-only arguments are not supported by getargspec()") args, varargs, varkw = inspect.getargs(code) return inspect.ArgSpec(args, varargs, varkw, func.__defaults__)
Example #6
Source File: bird.py From executing with MIT License | 6 votes |
def trace_function(self, func): # type: (FunctionType) -> FunctionType new_func = super(BirdsEye, self).trace_function(func) code_info = self._code_infos.get(new_func.__code__) if code_info: return new_func lines, start_lineno = inspect.getsourcelines(func) # type: List[Text], int end_lineno = start_lineno + len(lines) name = safe_qualname(func) source_file = inspect.getsourcefile(func) if source_file.startswith('<ipython-input'): filename = IPYTHON_FILE_PATH else: filename = os.path.abspath(source_file) traced_file = new_func.traced_file arg_info = inspect.getargs(new_func.__code__) arg_names = list(chain(flatten_list(arg_info[0]), arg_info[1:])) # type: List[str] self._trace(name, filename, traced_file, new_func.__code__, typ='function', start_lineno=start_lineno, end_lineno=end_lineno, arg_names=arg_names) return new_func
Example #7
Source File: shapes.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def _repr(self,I=None): '''return a repr style string with named fixed args first, then keywords''' if isinstance(self,float): return fp_str(self) elif isSeq(self): s = '' for v in self: s = s + '%s,' % _repr(v,I) if isinstance(self,list): return '[%s]' % s[:-1] else: return '(%s%s)' % (s[:-1],len(self)==1 and ',' or '') elif self is EmptyClipPath: if I: _addObjImport(self,I,'EmptyClipPath') return 'EmptyClipPath' elif isinstance(self,Shape): if I: _addObjImport(self,I) from inspect import getargs args, varargs, varkw = getargs(self.__init__.__func__.__code__) P = self.getProperties() s = self.__class__.__name__+'(' for n in args[1:]: v = P[n] del P[n] s = s + '%s,' % _repr(v,I) for n,v in P.items(): v = P[n] s = s + '%s=%s,' % (n, _repr(v,I)) return s[:-1]+')' else: return repr(self)
Example #8
Source File: Decorators.py From RMS with GNU General Public License v3.0 | 5 votes |
def normalize_args(self, args, kwargs): spec = inspect.getargs(self.func.__code__).args return dict(list(kwargs.items()) + list(zip(spec, args)))
Example #9
Source File: services.py From Azure-MachineLearning-ClientLibrary-Python with MIT License | 5 votes |
def _get_args(func): raw_schema = _get_dataframe_schema(func) if raw_schema is not None: return list(raw_schema.keys()) args = inspect.getargs(func.__code__) all_args = args.args if args.varargs is not None: all_args.append(args.varargs) if args.keywords is not None: all_args.append(args.keywords) return all_args
Example #10
Source File: turtle.py From Imogen with MIT License | 5 votes |
def getmethparlist(ob): """Get strings describing the arguments for the given object Returns a pair of strings representing function parameter lists including parenthesis. The first string is suitable for use in function definition and the second is suitable for use in function call. The "self" parameter is not included. """ defText = callText = "" # bit of a hack for methods - turn it into a function # but we drop the "self" param. # Try and build one for Python defined functions args, varargs, varkw = inspect.getargs(ob.__code__) items2 = args[1:] realArgs = args[1:] defaults = ob.__defaults__ or [] defaults = ["=%r" % (value,) for value in defaults] defaults = [""] * (len(realArgs)-len(defaults)) + defaults items1 = [arg + dflt for arg, dflt in zip(realArgs, defaults)] if varargs is not None: items1.append("*" + varargs) items2.append("*" + varargs) if varkw is not None: items1.append("**" + varkw) items2.append("**" + varkw) defText = ", ".join(items1) defText = "(%s)" % defText callText = ", ".join(items2) callText = "(%s)" % callText return defText, callText
Example #11
Source File: turtle.py From ironpython3 with Apache License 2.0 | 5 votes |
def getmethparlist(ob): """Get strings describing the arguments for the given object Returns a pair of strings representing function parameter lists including parenthesis. The first string is suitable for use in function definition and the second is suitable for use in function call. The "self" parameter is not included. """ defText = callText = "" # bit of a hack for methods - turn it into a function # but we drop the "self" param. # Try and build one for Python defined functions args, varargs, varkw = inspect.getargs(ob.__code__) items2 = args[1:] realArgs = args[1:] defaults = ob.__defaults__ or [] defaults = ["=%r" % (value,) for value in defaults] defaults = [""] * (len(realArgs)-len(defaults)) + defaults items1 = [arg + dflt for arg, dflt in zip(realArgs, defaults)] if varargs is not None: items1.append("*" + varargs) items2.append("*" + varargs) if varkw is not None: items1.append("**" + varkw) items2.append("**" + varkw) defText = ", ".join(items1) defText = "(%s)" % defText callText = ", ".join(items2) callText = "(%s)" % callText return defText, callText
Example #12
Source File: _inspect.py From ImageFusion with MIT License | 5 votes |
def getargspec(func): """Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. """ if ismethod(func): func = func.__func__ if not isfunction(func): raise TypeError('arg is not a Python function') args, varargs, varkw = getargs(func.__code__) return args, varargs, varkw, func.__defaults__
Example #13
Source File: _inspect.py From ImageFusion with MIT License | 5 votes |
def getargvalues(frame): """Get information about arguments passed into a particular frame. A tuple of four things is returned: (args, varargs, varkw, locals). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'locals' is the locals dictionary of the given frame.""" args, varargs, varkw = getargs(frame.f_code) return args, varargs, varkw, frame.f_locals
Example #14
Source File: shapes.py From stdm with GNU General Public License v2.0 | 5 votes |
def _repr(self,I=None): '''return a repr style string with named fixed args first, then keywords''' if type(self) is InstanceType: if self is EmptyClipPath: _addObjImport(self,I,'EmptyClipPath') return 'EmptyClipPath' if I: _addObjImport(self,I) if isinstance(self,Shape): from inspect import getargs args, varargs, varkw = getargs(self.__init__.im_func.func_code) P = self.getProperties() s = self.__class__.__name__+'(' for n in args[1:]: v = P[n] del P[n] s = s + '%s,' % _repr(v,I) for n,v in P.items(): v = P[n] s = s + '%s=%s,' % (n, _repr(v,I)) return s[:-1]+')' else: return repr(self) elif type(self) is FloatType: return fp_str(self) elif type(self) in (ListType,TupleType): s = '' for v in self: s = s + '%s,' % _repr(v,I) if type(self) is ListType: return '[%s]' % s[:-1] else: return '(%s%s)' % (s[:-1],len(self)==1 and ',' or '') else: return repr(self)
Example #15
Source File: turtle.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def getmethparlist(ob): """Get strings describing the arguments for the given object Returns a pair of strings representing function parameter lists including parenthesis. The first string is suitable for use in function definition and the second is suitable for use in function call. The "self" parameter is not included. """ defText = callText = "" # bit of a hack for methods - turn it into a function # but we drop the "self" param. # Try and build one for Python defined functions args, varargs, varkw = inspect.getargs(ob.__code__) items2 = args[1:] realArgs = args[1:] defaults = ob.__defaults__ or [] defaults = ["=%r" % (value,) for value in defaults] defaults = [""] * (len(realArgs)-len(defaults)) + defaults items1 = [arg + dflt for arg, dflt in zip(realArgs, defaults)] if varargs is not None: items1.append("*" + varargs) items2.append("*" + varargs) if varkw is not None: items1.append("**" + varkw) items2.append("**" + varkw) defText = ", ".join(items1) defText = "(%s)" % defText callText = ", ".join(items2) callText = "(%s)" % callText return defText, callText
Example #16
Source File: turtle.py From odoo13-x64 with GNU General Public License v3.0 | 5 votes |
def getmethparlist(ob): """Get strings describing the arguments for the given object Returns a pair of strings representing function parameter lists including parenthesis. The first string is suitable for use in function definition and the second is suitable for use in function call. The "self" parameter is not included. """ defText = callText = "" # bit of a hack for methods - turn it into a function # but we drop the "self" param. # Try and build one for Python defined functions args, varargs, varkw = inspect.getargs(ob.__code__) items2 = args[1:] realArgs = args[1:] defaults = ob.__defaults__ or [] defaults = ["=%r" % (value,) for value in defaults] defaults = [""] * (len(realArgs)-len(defaults)) + defaults items1 = [arg + dflt for arg, dflt in zip(realArgs, defaults)] if varargs is not None: items1.append("*" + varargs) items2.append("*" + varargs) if varkw is not None: items1.append("**" + varkw) items2.append("**" + varkw) defText = ", ".join(items1) defText = "(%s)" % defText callText = ", ".join(items2) callText = "(%s)" % callText return defText, callText
Example #17
Source File: Template.py From moviegrabber with GNU General Public License v3.0 | 5 votes |
def preprocess(self, source, file): """Create an intermediate template and return the source code it outputs """ settings = self._settings if not source: # @@TR: this needs improving if isinstance(file, (str, unicode)): # it's a filename. f = open(file) source = f.read() f.close() elif hasattr(file, 'read'): source = file.read() file = None templateAPIClass = settings.templateAPIClass possibleKwArgs = [ arg for arg in inspect.getargs(templateAPIClass.compile.im_func.func_code)[0] if arg not in ('klass', 'source', 'file',)] compileKwArgs = {} for arg in possibleKwArgs: if hasattr(settings, arg): compileKwArgs[arg] = getattr(settings, arg) tmplClass = templateAPIClass.compile(source=source, file=file, **compileKwArgs) tmplInstance = tmplClass(**settings.templateInitArgs) outputSource = settings.outputTransformer(tmplInstance) outputFile = None return outputSource, outputFile
Example #18
Source File: turtle.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def getmethparlist(ob): """Get strings describing the arguments for the given object Returns a pair of strings representing function parameter lists including parenthesis. The first string is suitable for use in function definition and the second is suitable for use in function call. The "self" parameter is not included. """ defText = callText = "" # bit of a hack for methods - turn it into a function # but we drop the "self" param. # Try and build one for Python defined functions args, varargs, varkw = inspect.getargs(ob.__code__) items2 = args[1:] realArgs = args[1:] defaults = ob.__defaults__ or [] defaults = ["=%r" % (value,) for value in defaults] defaults = [""] * (len(realArgs)-len(defaults)) + defaults items1 = [arg + dflt for arg, dflt in zip(realArgs, defaults)] if varargs is not None: items1.append("*" + varargs) items2.append("*" + varargs) if varkw is not None: items1.append("**" + varkw) items2.append("**" + varkw) defText = ", ".join(items1) defText = "(%s)" % defText callText = ", ".join(items2) callText = "(%s)" % callText return defText, callText
Example #19
Source File: turtle.py From android_universal with MIT License | 5 votes |
def getmethparlist(ob): """Get strings describing the arguments for the given object Returns a pair of strings representing function parameter lists including parenthesis. The first string is suitable for use in function definition and the second is suitable for use in function call. The "self" parameter is not included. """ defText = callText = "" # bit of a hack for methods - turn it into a function # but we drop the "self" param. # Try and build one for Python defined functions args, varargs, varkw = inspect.getargs(ob.__code__) items2 = args[1:] realArgs = args[1:] defaults = ob.__defaults__ or [] defaults = ["=%r" % (value,) for value in defaults] defaults = [""] * (len(realArgs)-len(defaults)) + defaults items1 = [arg + dflt for arg, dflt in zip(realArgs, defaults)] if varargs is not None: items1.append("*" + varargs) items2.append("*" + varargs) if varkw is not None: items1.append("**" + varkw) items2.append("**" + varkw) defText = ", ".join(items1) defText = "(%s)" % defText callText = ", ".join(items2) callText = "(%s)" % callText return defText, callText
Example #20
Source File: dochelpers.py From spyder-kernels with MIT License | 5 votes |
def getargs(obj): """Get the names and default values of a function's arguments""" if inspect.isfunction(obj) or inspect.isbuiltin(obj): func_obj = obj elif inspect.ismethod(obj): func_obj = get_meth_func(obj) elif inspect.isclass(obj) and hasattr(obj, '__init__'): func_obj = getattr(obj, '__init__') else: return [] if not hasattr(func_obj, 'func_code'): # Builtin: try to extract info from doc args = getargsfromdoc(func_obj) if args is not None: return args else: # Example: PyQt5 return getargsfromdoc(obj) args, _, _ = inspect.getargs(func_obj.func_code) if not args: return getargsfromdoc(obj) # Supporting tuple arguments in def statement: for i_arg, arg in enumerate(args): if isinstance(arg, list): args[i_arg] = "(%s)" % ", ".join(arg) defaults = get_func_defaults(func_obj) if defaults is not None: for index, default in enumerate(defaults): args[index+len(args)-len(defaults)] += '='+repr(default) if inspect.isclass(obj) or inspect.ismethod(obj): if len(args) == 1: return None if 'self' in args: args.remove('self') return args
Example #21
Source File: _inspect.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def getargspec(func): """Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. """ if ismethod(func): func = func.__func__ if not isfunction(func): raise TypeError('arg is not a Python function') args, varargs, varkw = getargs(func.__code__) return args, varargs, varkw, func.__defaults__
Example #22
Source File: _inspect.py From Computable with MIT License | 5 votes |
def getargspec(func): """Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. """ if ismethod(func): func = func.__func__ if not isfunction(func): raise TypeError('arg is not a Python function') args, varargs, varkw = getargs(func.__code__) return args, varargs, varkw, func.__defaults__
Example #23
Source File: _inspect.py From Computable with MIT License | 5 votes |
def getargvalues(frame): """Get information about arguments passed into a particular frame. A tuple of four things is returned: (args, varargs, varkw, locals). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'locals' is the locals dictionary of the given frame.""" args, varargs, varkw = getargs(frame.f_code) return args, varargs, varkw, frame.f_locals
Example #24
Source File: assembler.py From monasca-analytics with Apache License 2.0 | 5 votes |
def from_code(cls, code, copy_lineno=False): import inspect self = cls.from_spec(code.co_name, *inspect.getargs(code)) if copy_lineno: self.set_lineno(code.co_firstlineno) self.co_filename = code.co_filename self.co_freevars = code.co_freevars # XXX untested! return self
Example #25
Source File: utils.py From pipenv with MIT License | 5 votes |
def call_function_with_correct_args(fn, **provided_kwargs): # type: (Callable, Dict[str, Any]) -> Any """ Determines which arguments from **provided_kwargs** to call **fn** and calls it. Consumes a list of allowed arguments (e.g. from :func:`~inspect.getargs()`) and uses it to determine which of the arguments in the provided kwargs should be passed through to the given callable. :param Callable fn: A callable which has some dynamic arguments :param List[str] allowed_args: A list of allowed arguments which can be passed to the supplied function :return: The result of calling the function :rtype: Any """ # signature = inspect.signature(fn) args = [] kwargs = {} func_args, func_kwargs = get_allowed_args(fn) for arg in func_args: args.append(provided_kwargs[arg]) for arg in func_kwargs: if not provided_kwargs.get(arg): continue kwargs[arg] = provided_kwargs[arg] return fn(*args, **kwargs)
Example #26
Source File: models.py From pipenv with MIT License | 5 votes |
def _parse_provides_dict( cls, provides, # type: Dict[str, Callable] prepend_arg_to_callables=None, # type: Optional[str] ): # type: (...) -> Dict[str, Callable] creating_methods = False creating_classmethods = False if prepend_arg_to_callables is not None: if prepend_arg_to_callables == "self": creating_methods = True elif prepend_arg_to_callables == "cls": creating_classmethods = True provides_map = {} for item_name, item_value in provides.items(): if isinstance(item_value, ShimmedPath): item_value = item_value.shim() if inspect.isfunction(item_value): callable_args = inspect.getargs(item_value.__code__).args if "self" not in callable_args and creating_methods: item_value = make_method(item_value)(item_name) elif "cls" not in callable_args and creating_classmethods: item_value = make_classmethod(item_value)(item_name) elif isinstance(item_value, six.string_types): module_path, name = split_package(item_value) module = cls._import_module(module_path) item_value = getattr(module, name, None) if item_value is not None: provides_map[item_name] = item_value return provides_map
Example #27
Source File: utils.py From mne-features with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _get_feature_funcs(sfreq, module_name): """Inspection for feature functions. Inspects a given module and returns a dictionary of feature functions in this module. If the module does not contain any feature function, an empty dictionary is returned. Parameters ---------- sfreq : float Sampling rate of the data. module_name : str Name of the module to inspect. Returns ------- feature_funcs : dict """ feature_funcs = dict() res = getmembers(sys.modules[module_name], isfunction) for name, func in res: if name.startswith('compute_'): alias = name.split('compute_')[-1] if hasattr(func, 'func_code'): func_code = func.func_code else: func_code = func.__code__ args, _, _ = getargs(func_code) if 'sfreq' in args[0]: feature_funcs[alias] = partial(func, sfreq) else: feature_funcs[alias] = func return feature_funcs
Example #28
Source File: feature_extraction.py From mne-features with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_params(self, deep=True): """Get the parameters (if any) of the given feature function. Parameters ---------- deep : bool (default: True) If True, the method will get the parameters of the transformer. (See :class:`~sklearn.preprocessing.FunctionTransformer`). """ func_to_inspect = _get_python_func(self.func) # Get code object from the function if hasattr(func_to_inspect, 'func_code'): func_code = func_to_inspect.func_code else: func_code = func_to_inspect.__code__ args, _, _ = getargs(func_code) # Get defaults from the function if hasattr(func_to_inspect, 'defaults'): defaults = func_to_inspect.func_defaults else: defaults = func_to_inspect.__defaults__ if defaults is None: return dict() else: n_defaults = len(defaults) func_params = {key: value for key, value in zip(args[-n_defaults:], defaults)} if self.params is not None: func_params.update(self.params) return func_params
Example #29
Source File: view.py From osm-wikidata with GNU General Public License v3.0 | 5 votes |
def exception_handler(e): tb = get_current_traceback() last_frame = tb.frames[-1] last_frame_args = inspect.getargs(last_frame.code) return render_template('show_error.html', tb=tb, last_frame=last_frame, last_frame_args=last_frame_args), 500
Example #30
Source File: modelutils.py From hydpy with GNU Lesser General Public License v3.0 | 5 votes |
def argnames(self) -> List[str]: """The argument names of the current function. >>> from hydpy.cythons.modelutils import FuncConverter >>> from hydpy import prepare_model, pub >>> with pub.options.usecython(False): ... model = prepare_model('hland_v1') >>> FuncConverter(model, None, model.calc_tc_v1).argnames ['model'] """ return inspect.getargs(self.func.__code__)[0]