Skip to content

varname.helpers

module

varname.helpers

Some helper functions builtin based upon core features

Classes
  • Wrapper A wrapper with ability to retrieve the variable name</>
Functions
  • 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</>
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.

Parameters
  • frame (int, optional) The call stack index, indicating where this classis instantiated relative to where the variable is finally retrieved
  • 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 VarnameRetrievingError 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.
Examples
>>> @varname.register>>> class Foo: pass
>>> foo = Foo()
>>> # foo.__varname__ == 'foo'
>>>
>>> @varname.register
>>> def func():
>>>   return __varname__
>>> foo = func() # foo == 'foo'
Returns (Union)

The wrapper function or the class/function itselfif it is specified explictly.

class

varname.helpers.Wrapper(value, frame=1, ignore=None, raise_exc=True, strict=True)

A wrapper with ability to retrieve the variable name

Examples
>>> foo = Wrapper(True)>>> # foo.name == 'foo'
>>> # foo.value == True
>>> val = {}
>>> bar = Wrapper(val)
>>> # bar.name == 'bar'
>>> # bar.value is val
Parameters
  • value (Any) The value to be wrapped
  • raise_exc (bool, optional) Whether to raise exception when varname is failed to retrieve
  • strict (bool, optional) Whether to only return the variable name if the wrapper isassigned to it directly.
Attributes
  • name The variable name to which the instance is assigned
  • value The value this wrapper wraps
function

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.

Examples
>>> 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}
Parameters
  • *args (Any) The positional arguments
  • vars_only (bool, optional) Whether to only include variables in the output
  • frame (int, optional) The call stack index. You can understand this as the number ofwrappers around this function - 1.
  • **kwargs (Any) The keyword arguments
Returns (Dict)

A dict-like object

function

varname.helpers.debug(var, *more_vars, prefix='DEBUG: ', merge=False, repr=True, sep='=', vars_only=False)

Print variable names and values.

Examples
>>> 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>
Parameters
  • var The variable to print
  • *more_vars Other variables to print
  • prefix (str, optional) A prefix to print for each line
  • merge (bool, optional) Whether merge all variables in one line or not
  • repr (bool, optional) Print the value as repr(var)? otherwise str(var)
  • sep (str, optional) The separator between the variable name and value
function

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.

Examples
>>> 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'
Parameters
  • 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 fetch globals and locals from where the destination function (include the wrappers of this function) is called.
  • ignore (Union, optional) The intermediate calls to be ignored. See varname.ignoreNote that if both globals and locals are given, frame and ignore will be ignored.
  • **kwargs (Any) The keyword arguments to pass to exec.