varname.core
Provide core features for varname
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.</>
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
frame(int, optional) —Nth frame used to retrieve the variable name. This meansN-1intermediate frames will be skipped. Note that the frames matchignorewill not be counted. Seeignorefor details.ignore(Union, optional) — Frames to be ignored in order to reach theNth frame.These frames will not be counted to skip within thatN-1frames. 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,
aMaybeDecoratedFunctionWarningwill 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.
varnamepackage, python standardlibraries and lambda functions are ignored.- - A module (or filename of a module). Any calls from it and its
multi_vars(bool, optional) — Whether allow multiple variables on left-hand side (LHS).IfTrue, this function returns a tuple of the variable names, even there is only one variable on LHS. IfFalse, and multiple variables on LHS, aImproperUseErrorwill be raised.raise_exc(bool, optional) — Whether we should raise an exception if failedto retrieve the ast node. Note that set this toFalsewill NOT supress the exception when the use ofvarnameis improper (i.e. multiple variables on LHS withmulti_varsisFalse). SeeRaises/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 thana = [func()]
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.
ImproperUseError— When the use ofvarname()is improper, including:- - When LHS is not an
ast.Nameorast.Attributenode or not a
list/tuple of them - - When there are multiple variables on LHS but
multi_varsis False - - When
strictis True, but the result is not assigned to
variable(s) directly
raise_exc=Falsewill NOT suppress this exception.- - When LHS is not an
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) andraise_excis set toTrue.
varname.core.will(frame=1, raise_exc=True)
Detect the attribute name right immediately after a function call.
>>> 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!'
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 theImproperUseError
The attribute name right after the function call.None if ast node cannot be retrieved and raise_exc is False
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 byraise_exc=FalseVarnameRetrievingError— Whenraise_excisTrueand we failed todetect the attribute name (including not having one)
varname.core.nameof(var, *more_vars, frame=1, vars_only=True)
Get the names of the variables passed in
>>> 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.
var(Any) — The variable to retrieve the name of*more_vars(Any) — Other variables to retrieve the names offrame(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. IfFalse, then the sources of the arguments will be returned.
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".
VarnameRetrievingError— When the callee's node cannot be retrieved ortrying to retrieve the full name of non attribute series calls.
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.
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.
Star argument is also allowed:def func(args, *kwargs): return argname('args[0]', 'kwargs[x]') # no quote needed
Note the difference:def func(args, x = 1): return argname('args', 'x') a = b = c = 1 func(a, b, x=c) # ('a', 'b', 'c')
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.idwill
be used to get the function fromlocals()orglobals(). - - If variable (ast.Name), attributes (ast.Attribute),
subscripts (ast.Subscript), and combinations of those and
literals used as function,pure_evalwill be used to evaluate
the node - - If
pure_evalis not installed or failed to evaluate,eval
will be used. A warning will be shown since unwanted side
effects may happen in this case.
- - If a variable (ast.Name) used as function, the
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, expectfuncto 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. Seevarname.ignorevars_only(bool, optional) — Require the arguments to be variables only.If False,asttokensis required to retrieve the source.
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")
ImproperUseError— When frame or func is incorrectly specified.VarnameRetrievingError— When the ast node where the function is calledcannot be retrieved