Skip to content

varname.core

module

varname.core

Provide core features for varname

Functions
  • argname(arg, *more_args, func, dispatch, frame, ignore, vars_only) (Union) Get the names/sources of arguments passed to a function.</>
  • nameof(var, *more_vars, frame, vars_only) (Union) Get the names of the variables passed in</>
  • varname(frame, ignore, multi_vars, raise_exc, strict) (Union) Get the name of the variable(s) that assigned by function call orclass instantiation. </>
  • will(frame, raise_exc) (str) Detect the attribute name right immediately after a function call.</>
function

varname.core.varname(frame=1, ignore=None, multi_vars=False, raise_exc=True, strict=True)

Get the name of the variable(s) that assigned by function call orclass instantiation.

To debug and specify the right frame and ignore arguments, you can set debug on and see how the frames are ignored or selected:

>>> from varname import config
>>> config.debug = True
Parameters
  • frame (int, optional) Nth frame used to retrieve the variable name. This meansN-1 intermediate frames will be skipped. Note that the frames match ignore will not be counted. See ignore for details.
  • ignore (Union, optional) Frames to be ignored in order to reach the Nth frame.These frames will not be counted to skip within that N-1 frames. You can specify:
    • - A module (or filename of a module). Any calls from it and its
        submodules will be ignored.
    • - A function. If it looks like it might be a decorated function,
        a MaybeDecoratedFunctionWarning will be shown.
    • - Tuple of a function and a number of additional frames that should
        be skipped just before reaching this function in the stack.
        This is typically used for functions that have been decorated
        with a 'classic' decorator that replaces the function with
        a wrapper. In that case each such decorator involved should
        be counted in the number that's the second element of the tuple.
    • - Tuple of a module (or filename) and qualified name (qualname).
        You can use Unix shell-style wildcards to match the qualname.
        Otherwise the qualname must appear exactly once in the
        module/file.
    By default, all calls from varname package, python standardlibraries and lambda functions are ignored.
  • multi_vars (bool, optional) Whether allow multiple variables on left-hand side (LHS).If True, this function returns a tuple of the variable names, even there is only one variable on LHS. If False, and multiple variables on LHS, a ImproperUseError will be raised.
  • raise_exc (bool, optional) Whether we should raise an exception if failedto retrieve the ast node. Note that set this to False will NOT supress the exception when the use of varname is improper (i.e. multiple variables on LHS with multi_vars is False). See Raises/ImproperUseError.
  • strict (bool, optional) Whether to only return the variable name(s) if the result ofthe call is assigned to it/them directly. For example, a = func() rather than a = [func()]
Returns (Union)

The variable name, or None when raise_exc is False and we failed to retrieve the ast node for the variable(s). A tuple or a hierarchy (tuple of tuples) of variable names when multi_vars is True.

Raises
  • ImproperUseError When the use of varname() is improper, including:
    • - When LHS is not an ast.Name or ast.Attribute node or not a
        list/tuple of them
    • - When there are multiple variables on LHS but multi_vars is False
    • - When strict is True, but the result is not assigned to
        variable(s) directly
    Note that raise_exc=False will NOT suppress this exception.
  • MultiTargetAssignmentWarning When there are multiple targetin the assign node. (e.g: a = b = func(), in such a case, a == 'b', may not be the case you want)
  • VarnameRetrievingError When we are unable to retrieve the ast nodefor the variable(s) and raise_exc is set to True.
function

varname.core.will(frame=1, raise_exc=True)

Detect the attribute name right immediately after a function call.

Examples
>>> class AwesomeClass:>>>     def __init__(self):
>>>         self.will = None
>>>     def permit(self):
>>>         self.will = will()
>>>         if self.will == 'do':
>>>             # let self handle do
>>>             return self
>>>         raise AttributeError(
>>>             'Should do something with AwesomeClass object'
>>>         )
>>>     def do(self):
>>>         if self.will != 'do':
>>>             raise AttributeError("You don't have permission to do")
>>>         return 'I am doing!'
>>> awesome = AwesomeClass()
>>> # AttributeError: You don't have permission to do
>>> awesome.do()
>>> # AttributeError: Should do something with AwesomeClass object
>>> awesome.permit()
>>> awesome.permit().do() == 'I am doing!'
Parameters
  • frame (int, optional) At which frame this function is called.
  • raise_exc (bool, optional) Raise exception we failed to detect the ast nodeThis will NOT supress the ImproperUseError
Returns (str)

The attribute name right after the function call.None if ast node cannot be retrieved and raise_exc is False

Raises
  • ImproperUseError When (the wraper of) this function is not calledinside a method/property of a class instance. Note that this exception will not be suppressed by raise_exc=False
  • VarnameRetrievingError When raise_exc is True and we failed todetect the attribute name (including not having one)
function

varname.core.nameof(var, *more_vars, frame=1, vars_only=True)

Get the names of the variables passed in

Examples
>>> a = 1>>> nameof(a) # 'a'
>>> b = 2
>>> nameof(a, b) # ('a', 'b')
>>> x = lambda: None
>>> x.y = 1
>>> nameof(x.y, vars_only=False) # 'x.y'

Note

This function works with the environments where source code is available, in other words, the callee's node can be retrieved by executing. In some cases, for example, running code from python shell/REPL or from exec/eval, we try to fetch the variable name from the bytecode. This requires only a single variable name is passed to this function and no keyword arguments, meaning that getting full names of attribute calls are not supported in such cases.

Parameters
  • var (Any) The variable to retrieve the name of
  • *more_vars (Any) Other variables to retrieve the names of
  • frame (int, optional) The this function is called from the wrapper of it. frame=1means no wrappers. Note that the calls from standard libraries are ignored. Also note that the wrapper has to have signature as this one.
  • vars_only (bool, optional) Whether only allow variables/attributes as arguments orany expressions. If False, then the sources of the arguments will be returned.
Returns (Union)

The names/sources of variables/expressions passed in. If a single argument is passed, return the name/source of it. If multiple variables are passed, return a tuple of their names/sources. If the argument is an attribute (e.g. a.b) and vars_only is True, only "b" will returned. Set vars_only to False to get "a.b".

Raises
  • VarnameRetrievingError When the callee's node cannot be retrieved ortrying to retrieve the full name of non attribute series calls.
function

varname.core.argname(arg, *more_args, func=None, dispatch=None, frame=1, ignore=None, vars_only=True)

Get the names/sources of arguments passed to a function.

Instead of passing the argument variables themselves to this function (like argname() does), you should pass their names instead.

Parameters
  • arg (str) and
  • *more_args (str) The names of the arguments that you want to retrievenames/sources of. You can also use subscripts to get parts of the results.
    def func(args, *kwargs): return argname('args[0]', 'kwargs[x]') # no quote needed
    Star argument is also allowed:
    def func(args, x = 1): return argname('args', 'x') a = b = c = 1 func(a, b, x=c) # ('a', 'b', 'c')
    Note the difference:
    def func(*args, x = 1): return argname('args', 'x') a = b = c = 1 func(a, b, x=c) # (('a', 'b'), 'c')
  • func (Callable, optional) The target function. If not provided, the AST node of thefunction call will be used to fetch the function:
    • - If a variable (ast.Name) used as function, the node.id will
        be used to get the function from locals() or globals().
    • - If variable (ast.Name), attributes (ast.Attribute),
        subscripts (ast.Subscript), and combinations of those and
        literals used as function, pure_eval will be used to evaluate
        the node
    • - If pure_eval is not installed or failed to evaluate, eval
        will be used. A warning will be shown since unwanted side
        effects may happen in this case.
    You are very encouraged to always pass the function explicitly.
  • dispatch (Type, optional) If a function is a single-dispatched function, you canspecify a type for it to dispatch the real function. If this is specified, expect func to be the generic function if provided.
  • frame (int, optional) The frame where target function is called from this call.Calls from python standard libraries are ignored.
  • ignore (Union, optional) The intermediate calls to be ignored. See varname.ignore
  • vars_only (bool, optional) Require the arguments to be variables only.If False, asttokens is required to retrieve the source.
Returns (Union)

The argument source when no more_args passed, otherwise a tuple ofargument sources Note that when an argument is an ast.Constant, repr(arg.value) is returned, so argname() return 'a' for func("a")

Raises
  • ImproperUseError When frame or func is incorrectly specified.
  • VarnameRetrievingError When the ast node where the function is calledcannot be retrieved