Python inspect.getargvalues() Examples

The following are 30 code examples of inspect.getargvalues(). 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: core.py    From django-more with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def super_patchy(*args, do_call=True, **kwargs):
    """ super() for patches!
        When called from within a patched in function will return or call the
        function that it replaced, preserving self/cls arguments
    """
    caller_frame = inspect.currentframe().f_back
    caller = inspect.getargvalues(caller_frame)

    old_func = patchy_records[caller_frame.f_code]

    if caller.args[0] in ['self', 'cls']:
        # If caller has the appearance of being bound (to instance or class)
        old_func = MethodType(old_func, caller.locals[caller.args[0]])
    if do_call:
        return old_func(*args, **kwargs)
    return old_func 
Example #2
Source File: io.py    From modin with Apache License 2.0 6 votes vote down vote up
def read_hdf(
    path_or_buf,
    key=None,
    mode: str = "r",
    errors: str = "strict",
    where=None,
    start: Optional[int] = None,
    stop: Optional[int] = None,
    columns=None,
    iterator=False,
    chunksize: Optional[int] = None,
    **kwargs,
):
    _, _, _, kwargs = inspect.getargvalues(inspect.currentframe())
    kwargs.update(kwargs.pop("kwargs", {}))

    from modin.data_management.dispatcher import EngineDispatcher

    return DataFrame(query_compiler=EngineDispatcher.read_hdf(**kwargs)) 
Example #3
Source File: mgp_en.py    From flare with MIT License 6 votes vote down vote up
def __init__(self, grid_num: int, bounds, bond_struc: Structure,
                 svd_rank=0, mean_only: bool=False, n_cpus: int=None,
                 n_sample: int=100):
        '''
        Build 2-body MGP

        bond_struc: Mock structure used to sample 2-body forces on 2 atoms
        '''

        self.grid_num = grid_num
        self.bounds = bounds
        self.bond_struc = bond_struc
        self.svd_rank = svd_rank
        self.mean_only = mean_only
        self.n_cpus = n_cpus
        self.n_sample = n_sample

        spc = bond_struc.coded_species
        self.species_code = Z_to_element(spc[0]) + '_' + Z_to_element(spc[1])

#        arg_dict = inspect.getargvalues(inspect.currentframe())[3]
#        del arg_dict['self']
#        self.__dict__.update(arg_dict)

        self.build_map_container() 
Example #4
Source File: io.py    From modin with Apache License 2.0 6 votes vote down vote up
def read_html(
    io,
    match=".+",
    flavor=None,
    header=None,
    index_col=None,
    skiprows=None,
    attrs=None,
    parse_dates=False,
    thousands=",",
    encoding=None,
    decimal=".",
    converters=None,
    na_values=None,
    keep_default_na=True,
    displayed_only=True,
):
    _, _, _, kwargs = inspect.getargvalues(inspect.currentframe())

    from modin.data_management.dispatcher import EngineDispatcher

    return DataFrame(query_compiler=EngineDispatcher.read_html(**kwargs)) 
Example #5
Source File: io.py    From modin with Apache License 2.0 6 votes vote down vote up
def read_stata(
    filepath_or_buffer,
    convert_dates=True,
    convert_categoricals=True,
    index_col=None,
    convert_missing=False,
    preserve_dtypes=True,
    columns=None,
    order_categoricals=True,
    chunksize=None,
    iterator=False,
):
    _, _, _, kwargs = inspect.getargvalues(inspect.currentframe())

    from modin.data_management.dispatcher import EngineDispatcher

    return DataFrame(query_compiler=EngineDispatcher.read_stata(**kwargs)) 
Example #6
Source File: io.py    From modin with Apache License 2.0 6 votes vote down vote up
def read_gbq(
    query: str,
    project_id: Optional[str] = None,
    index_col: Optional[str] = None,
    col_order: Optional[List[str]] = None,
    reauth: bool = False,
    auth_local_webserver: bool = False,
    dialect: Optional[str] = None,
    location: Optional[str] = None,
    configuration: Optional[Dict[str, Any]] = None,
    credentials=None,
    use_bqstorage_api: Optional[bool] = None,
    private_key=None,
    verbose=None,
    progress_bar_type: Optional[str] = None,
) -> DataFrame:
    _, _, _, kwargs = inspect.getargvalues(inspect.currentframe())
    kwargs.update(kwargs.pop("kwargs", {}))

    from modin.data_management.dispatcher import EngineDispatcher

    return DataFrame(query_compiler=EngineDispatcher.read_gbq(**kwargs)) 
Example #7
Source File: helpers.py    From quark with Apache License 2.0 6 votes vote down vote up
def extract_ast_stack(frames):
    ast_stack = []
    ast_seen = []
    for frame in frames:
        ast_frame = []
        a = inspect.getargvalues(frame[0])
        def tryget(x,a=a):
            try:
                return a.locals.get(x)
            except (TypeError, KeyError):
                pass
        args = map(tryget, a.args)
        if a.varargs:
            args.extend(a.locals[a.varargs])
        if a.keywords:
            args.extend(v for k,v in sorted(a.locals[a.keywords].items()))
        for arg in args:
            if isinstance(arg, AST) and arg not in ast_seen:
                ast_seen.append(arg)
                ast_frame.append(arg)
        if ast_frame:
            ast_stack.append(ast_frame)

    return ast_stack 
Example #8
Source File: io.py    From modin with Apache License 2.0 6 votes vote down vote up
def read_fwf(
    filepath_or_buffer: Union[str, pathlib.Path, IO[AnyStr]],
    colspecs="infer",
    widths=None,
    infer_nrows=100,
    **kwds,
):
    from modin.data_management.dispatcher import EngineDispatcher

    _, _, _, kwargs = inspect.getargvalues(inspect.currentframe())
    kwargs.update(kwargs.pop("kwds", {}))
    pd_obj = EngineDispatcher.read_fwf(**kwargs)
    # When `read_fwf` returns a TextFileReader object for iterating through
    if isinstance(pd_obj, pandas.io.parsers.TextFileReader):
        reader = pd_obj.read
        pd_obj.read = lambda *args, **kwargs: DataFrame(
            query_compiler=reader(*args, **kwargs)
        )
        return pd_obj
    return DataFrame(query_compiler=pd_obj) 
Example #9
Source File: io.py    From modin with Apache License 2.0 6 votes vote down vote up
def read_json(
    path_or_buf=None,
    orient=None,
    typ="frame",
    dtype=None,
    convert_axes=None,
    convert_dates=True,
    keep_default_dates=True,
    numpy=False,
    precise_float=False,
    date_unit=None,
    encoding=None,
    lines=False,
    chunksize=None,
    compression="infer",
):
    _, _, _, kwargs = inspect.getargvalues(inspect.currentframe())

    from modin.data_management.dispatcher import EngineDispatcher

    return DataFrame(query_compiler=EngineDispatcher.read_json(**kwargs)) 
Example #10
Source File: utils.py    From cgat-core with MIT License 6 votes vote down vote up
def get_caller_locals(decorators=0):
    '''returns the locals of the calling function.

    from http://pylab.blogspot.com/2009/02/
         python-accessing-caller-locals-from.html

    Arguments
    ---------
    decorators : int
        Number of contexts to go up to reach calling function
        of interest.

    Returns
    -------
    locals : dict
        Dictionary of variable defined in the context of the
        calling function.
    '''
    f = sys._getframe(2 + decorators)
    args = inspect.getargvalues(f)
    return args[3] 
Example #11
Source File: parsing.py    From pytorch-lightning with Apache License 2.0 6 votes vote down vote up
def collect_init_args(frame, path_args: list, inside: bool = False) -> list:
    """
    Recursively collects the arguments passed to the child constructors in the inheritance tree.

    Args:
        frame: the current stack frame
        path_args: a list of dictionaries containing the constructor args in all parent classes
        inside: track if we are inside inheritance path, avoid terminating too soon

    Return:
          A list of dictionaries where each dictionary contains the arguments passed to the
          constructor at that level. The last entry corresponds to the constructor call of the
          most specific class in the hierarchy.
    """
    _, _, _, local_vars = inspect.getargvalues(frame)
    if '__class__' in local_vars:
        local_args = get_init_args(frame)
        # recursive update
        path_args.append(local_args)
        return collect_init_args(frame.f_back, path_args, inside=True)
    elif not inside:
        return collect_init_args(frame.f_back, path_args, inside)
    else:
        return path_args 
Example #12
Source File: debug.py    From omniduct with MIT License 6 votes vote down vote up
def detect_scopes():
    scopes = []
    current_frame = inspect.currentframe()

    while current_frame is not None:
        if current_frame.f_code.co_name == 'logging_scope':
            scopes.append(current_frame.f_locals['name'])
        else:
            argvalues = inspect.getargvalues(current_frame)
            if 'self' in argvalues.args and getattr(argvalues.locals['self'].__class__, 'AUTO_LOGGING_SCOPE',
                                                    False):
                scopes.append(argvalues.locals['self'])
        current_frame = current_frame.f_back

    out_scopes = []
    seen = set()
    for scope in scopes[::-1]:
        if scope not in seen:
            out_scopes.append(
                scope
                if isinstance(scope, six.string_types) else
                (getattr(scope, "LOGGING_SCOPE", None) or getattr(scope, "name", None) or scope.__class__.__name__))
            seen.add(scope)
    return out_scopes 
Example #13
Source File: parsing.py    From pytorch-lightning with Apache License 2.0 6 votes vote down vote up
def get_init_args(frame) -> dict:
    _, _, _, local_vars = inspect.getargvalues(frame)
    if '__class__' not in local_vars:
        return
    cls = local_vars['__class__']
    spec = inspect.getfullargspec(cls.__init__)
    init_parameters = inspect.signature(cls.__init__).parameters
    self_identifier = spec.args[0]  # "self" unless user renames it (always first arg)
    varargs_identifier = spec.varargs  # by convention this is named "*args"
    kwargs_identifier = spec.varkw  # by convention this is named "**kwargs"
    exclude_argnames = (
        varargs_identifier, kwargs_identifier, self_identifier, '__class__', 'frame', 'frame_args'
    )

    # only collect variables that appear in the signature
    local_args = {k: local_vars[k] for k in init_parameters.keys()}
    local_args.update(local_args.get(kwargs_identifier, {}))
    local_args = {k: v for k, v in local_args.items() if k not in exclude_argnames}
    return local_args 
Example #14
Source File: proxyplugins.py    From MITMf with GNU General Public License v3.0 5 votes vote down vote up
def hook(self):
        '''Magic to hook various function calls in sslstrip'''
        #gets the function name and args of our caller
        frame = sys._getframe(1)
        fname = frame.f_code.co_name
        keys,_,_,values = inspect.getargvalues(frame)

        #assumes that no one calls del on an arg :-/
        args = {}
        for key in keys:
            args[key] = values[key]
    
        #prevent self conflict
        if (fname == "handleResponse") or (fname == "handleHeader") or (fname == "handleEndHeaders"):
            args['request']  = args['self']
            args['response'] = args['self'].client
        else:
            args['request'] = args['self']

        del args['self']

        log.debug("hooking {}()".format(fname))
        #calls any plugin that has this hook
        try:
            if self.plugin_mthds:
                for f in self.plugin_mthds[fname]:
                    a = f(**args)
                    if a != None: args = a
        except Exception as e:
            #This is needed because errors in hooked functions won't raise an Exception + Traceback (which can be infuriating)
            log.error("Exception occurred in hooked function")
            traceback.print_exc()

        #pass our changes to the locals back down
        return args 
Example #15
Source File: test_inspect.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_frame(self):
        args, varargs, varkw, locals = inspect.getargvalues(mod.fr)
        self.assertEqual(args, ['x', 'y'])
        self.assertEqual(varargs, None)
        self.assertEqual(varkw, None)
        self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14})
        self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
                         '(x=11, y=14)') 
Example #16
Source File: test_inspect.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_frame(self):
        args, varargs, varkw, locals = inspect.getargvalues(mod.fr)
        self.assertEqual(args, ['x', 'y'])
        self.assertEqual(varargs, None)
        self.assertEqual(varkw, None)
        self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14})
        self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
                         '(x=11, y=14)') 
Example #17
Source File: models.py    From python-sms-activate-ru with Apache License 2.0 5 votes vote down vote up
def _build(self, frame):
		args, _, _, values = inspect.getargvalues(frame)
		exclude = ['self', 'callback', 'wrapper']
		result = {}
		for i in args:
			if i == 'ref':
				values[i] = 'python' + __name__.split('.')[0][:-2]
			elif not values[i]:
				continue
			if i in exclude:
				continue
			result[i] = values[i]
		return result 
Example #18
Source File: ze_utils.py    From x-vector-kaldi-tf with Apache License 2.0 5 votes vote down vote up
def print_function_args_values(frame):
    args, _, _, values = inspect.getargvalues(frame)
    print('Function name "%s"' % inspect.getframeinfo(frame)[2])
    for arg in args:
        print("    %s = %s" % (arg, values[arg])) 
Example #19
Source File: debug.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def frameInfo(self, fr):
        filename = fr.f_code.co_filename
        funcname = fr.f_code.co_name
        lineno = fr.f_lineno
        callfr = sys._getframe(3)
        callline = "%s %d" % (callfr.f_code.co_name, callfr.f_lineno)
        args, _, _, value_dict = inspect.getargvalues(fr)
        if len(args) and args[0] == 'self':
            instance = value_dict.get('self', None)
            if instance is not None:
                cls = getattr(instance, '__class__', None)
                if cls is not None:
                    funcname = cls.__name__ + "." + funcname
        return "%s: %s %s: %s" % (callline, filename, lineno, funcname) 
Example #20
Source File: xtgeo_dialog.py    From xtgeo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _get_class_from_frame(fr):
        # pylint: disable=deprecated-method
        args, _, _, value_dict = inspect.getargvalues(fr)

        # we check the first parameter for the frame function is
        # named 'self'
        if args and args[0] == "self":
            instance = value_dict.get("self", None)
            if instance:
                # return its class
                return getattr(instance, "__class__", None)
        # return None otherwise
        return None 
Example #21
Source File: test_inspect.py    From medicare-demo with Apache License 2.0 5 votes vote down vote up
def test_frame(self):
        args, varargs, varkw, locals = inspect.getargvalues(mod.fr)
        self.assertEqual(args, ['x', 'y'])
        self.assertEqual(varargs, None)
        self.assertEqual(varkw, None)
        self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14})
        self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
                         '(x=11, y=14)')

    # TODO - test_previous_frame could be rewritten such that we could
    # introspect on the previous frame but without a dependency on
    # tuple unpacking 
Example #22
Source File: test_inspect.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_previous_frame(self):
        args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back)
        self.assertEqual(args, ['a', 'b', 'c', 'd', 'e', 'f'])
        self.assertEqual(varargs, 'g')
        self.assertEqual(varkw, 'h')
        self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
             '(a=7, b=8, c=9, d=3, e=4, f=5, *g=(), **h={})') 
Example #23
Source File: rgf.py    From kaggle_otto with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_params_string(self, train_x_fn=None, train_y_fn=None, test_x_fn=None, test_y_fn=None,
                          model_fn=None, model_fn_prefix=None, evaluation_fn=None, prediction_fn=None,
                          reg_L2=None, reg_sL2=None, algorithm=None, loss=None,
                          test_interval=None, max_tree=None, max_leaf_forest=None):
        frame = inspect.currentframe()
        args, _, _, values = inspect.getargvalues(frame)
        params_string = ''

        for arg in args:
            if values[arg] is not None and arg != 'self':
                params_string += '%s=%s,' % (arg, values[arg])

        return params_string 
Example #24
Source File: nav_base.py    From plugin.video.openmeta with GNU General Public License v3.0 5 votes vote down vote up
def caller_args():
	caller = inspect.stack()[2][0]
	args, _, _, values = inspect.getargvalues(caller)
	return dict([(i, values[i]) for i in args]) 
Example #25
Source File: introspect.py    From incubator-sdap-nexus with Apache License 2.0 5 votes vote down vote up
def myArgs():
    """Return the arguments of the executing function (the caller of myArgs)."""
    return getargvalues(currentframe().f_back)[3] 
Example #26
Source File: layers.py    From fold with Apache License 2.0 5 votes vote down vote up
def get_local_arguments(fun, is_method=False):
  """Return the callers arguments and non-default keyword arguments.

  Args:
    fun: The function or method that is calling get_local_arguments.
    is_method: True if this is a method with a self argument.

  Returns:
    A tuple of (list of arguments, list of non default keyword arguments)
  """

  frame = inspect.currentframe().f_back
  argvals = inspect.getargvalues(frame)
  argspec = inspect.getargspec(fun)

  lvals = argvals.locals
  num_args = len(argspec.args) - len(argspec.defaults)
  arg_names = argspec.args[0:num_args]
  kwarg_names = argspec.args[num_args:]

  args = [lvals[k] for k in arg_names]
  kwargs_a = [(k, lvals[k], d) for (k, d) in zip(kwarg_names, argspec.defaults)]
  kwargs = [(k, v) for (k, v, d) in kwargs_a if v != d]

  if is_method: args = args[1:]   # strip off the self argument
  return (args, kwargs) 
Example #27
Source File: test_inspect.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_previous_frame(self):
        args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back)
        self.assertEqual(args, ['a', 'b', 'c', 'd', ['e', ['f']]])
        self.assertEqual(varargs, 'g')
        self.assertEqual(varkw, 'h')
        self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
             '(a=7, b=8, c=9, d=3, (e=4, (f=5,)), *g=(), **h={})') 
Example #28
Source File: test_inspect.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_frame(self):
        args, varargs, varkw, locals = inspect.getargvalues(mod.fr)
        self.assertEqual(args, ['x', 'y'])
        self.assertEqual(varargs, None)
        self.assertEqual(varkw, None)
        self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14})
        self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
                         '(x=11, y=14)') 
Example #29
Source File: base.py    From luna with GNU General Public License v3.0 5 votes vote down vote up
def _debug_function(self):
        """Outputs the calling function's name and it's arguments"""

        if logging.getLogger().getEffectiveLevel() != 10:
            return None

        caller = inspect.currentframe().f_back
        f_name = inspect.getframeinfo(caller)[2]
        _, _, _, values = inspect.getargvalues(caller)

        return (f_name, values) 
Example #30
Source File: operators.py    From BlenderRobotDesigner with GNU General Public License v2.0 5 votes vote down vote up
def pass_keywords():
        """
        Helper function that extracts the arguments of the callee (must be a (class) method) and returns them.

        Credits to `Kelly Yancey <http://kbyanc.blogspot.de/2007/07/python-aggregating-function-arguments.html>`_
        """

        args, _, _, locals = inspect.getargvalues(inspect.stack()[1][0])
        args.pop(0)
        kwargs = {i: j for i, j in locals.items() if i in args}
        return kwargs