varname.helpers
Some helper functions builtin based upon core features
debug
(
var
,*more_vars
,prefix
,merge
,repr
,sep
,vars_only
)
— Print variable names and values.</>exec_code
(
code
,globals
,locals
,sourcefile
,frame
,ignore
,**kwargs
)
— Execute code where source code is visible at runtime.</>jsobj
(
*args
,vars_only
,frame
,**kwargs
)
(Dict) — A wrapper to create a JavaScript-like object</>register
(
cls_or_func
,frame
,ignore
,multi_vars
,raise_exc
,strict
)
(Union) — A decorator to register varname to a class or function</>
varname.helpers.
register
(
cls_or_func=None
, frame=1
, ignore=None
, multi_vars=False
, raise_exc=True
, strict=True
)
A decorator to register varname to a class or function
When registered to a class, it can be accessed by self.__varname__
;
while to a function, it is registered to globals, meaning that it can be
accessed directly.
frame
(int, optional) — The call stack index, indicating where this classis instantiated relative to where the variable is finally retrievedmulti_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, aVarnameRetrievingError
will be raised.raise_exc
(bool, optional) — Whether we should raise an exception if failedto retrieve the name.strict
(bool, optional) — Whether to only return the variable name if the result ofthe call is assigned to it directly.
>>> @varname.register>>> class Foo: pass
>>> foo = Foo()
>>> # foo.__varname__ == 'foo'
>>>
>>> @varname.register
>>> def func():
>>> return __varname__
>>> foo = func() # foo == 'foo'
The wrapper function or the class/function itselfif it is specified explictly.
varname.helpers.
Wrapper
(
value
, frame=1
, ignore=None
, raise_exc=True
, strict=True
)
A wrapper with ability to retrieve the variable name
>>> foo = Wrapper(True)>>> # foo.name == 'foo'
>>> # foo.value == True
>>> val = {}
>>> bar = Wrapper(val)
>>> # bar.name == 'bar'
>>> # bar.value is val
value
(Any) — The value to be wrappedraise_exc
(bool, optional) — Whether to raise exception when varname is failed to retrievestrict
(bool, optional) — Whether to only return the variable name if the wrapper isassigned to it directly.
name
— The variable name to which the instance is assignedvalue
— The value this wrapper wraps
varname.helpers.
jsobj
(
*args
, vars_only=True
, frame=1
, **kwargs
)
A wrapper to create a JavaScript-like object
When an argument is passed as positional argument, the name of the variable will be used as the key, while the value will be used as the value.
>>> obj = jsobj(a=1, b=2)>>> # obj == {'a': 1, 'b': 2}
>>> # obj.a == 1
>>> # obj.b == 2
>>> a = 1
>>> b = 2
>>> obj = jsobj(a, b, c=3)
>>> # obj == {'a': 1, 'b': 2, 'c': 3}
*args
(Any) — The positional argumentsvars_only
(bool, optional) — Whether to only include variables in the outputframe
(int, optional) — The call stack index. You can understand this as the number ofwrappers around this function - 1.**kwargs
(Any) — The keyword arguments
A dict-like object
varname.helpers.
debug
(
var
, *more_vars
, prefix='DEBUG: '
, merge=False
, repr=True
, sep='='
, vars_only=False
)
Print variable names and values.
>>> a = 1>>> b = object
>>> print(f'a={a}') # previously, we have to do
>>> print(f'{a=}') # or with python3.8
>>> # instead we can do:
>>> debug(a) # DEBUG: a=1
>>> debug(a, prefix='') # a=1
>>> debug(a, b, merge=True) # a=1, b=<object object at 0x2b9a4c89cf00>
var
— The variable to print*more_vars
— Other variables to printprefix
(str, optional) — A prefix to print for each linemerge
(bool, optional) — Whether merge all variables in one line or notrepr
(bool, optional) — Print the value asrepr(var)
? otherwisestr(var)
sep
(str, optional) — The separator between the variable name and value
varname.helpers.
exec_code
(
code
, globals=None
, locals=None
, sourcefile=None
, frame=1
, ignore=None
, **kwargs
)
Execute code where source code is visible at runtime.
This function is useful when you want to execute some code, where you want to retrieve the AST node of the code at runtime. This function will create a temporary file and write the code into it, then execute the code in the file.
>>> from varname import varname>>> def func(): return varname()
>>> exec('var = func()') # VarnameRetrievingError:
>>> # Unable to retrieve the ast node.
>>> from varname.helpers import code_exec
>>> code_exec('var = func()') # var == 'var'
code
(str) — The code to execute.globals
(Dict, optional) — The globals to use.locals
(Dict, optional) — The locals to use.sourcefile
(os.pathlike | str, optional) — The source file to write the code into.if not given, a temporary file will be used. This file will be deleted after the code is executed.frame
(int, optional) — The call stack index. You can understand this as the number ofwrappers around this function. This is used to fetchglobals
andlocals
from where the destination function (include the wrappers of this function) is called.ignore
(Union, optional) — The intermediate calls to be ignored. Seevarname.ignore
Note that if bothglobals
andlocals
are given,frame
andignore
will be ignored.**kwargs
(Any) — The keyword arguments to pass toexec
.