Dark magics about variable names in python
npx @tessl/cli install tessl/pypi-varname@0.15.0Dark magics about variable names in Python. Varname provides runtime introspection capabilities to retrieve variable names, function argument names, and detect attribute access patterns through AST inspection and stack frame analysis.
pip install varnamefrom varname import varname, nameof, will, argnameImporting exceptions, configuration, and version info:
from varname import (
VarnameException,
VarnameRetrievingError,
ImproperUseError,
config,
__version__
)Importing helper functions:
from varname.helpers import register, Wrapper, jsobj, debug, exec_codeImporting ignore system classes:
from varname.ignore import IgnoreModule, IgnoreFunction, IgnoreList__version__: str = "0.15.0"from varname import varname, nameof, will, argname
# Get variable name from function assignment
def create_data():
return varname()
my_data = create_data() # my_data == 'my_data'
# Get names of variables passed to function
x = 1
y = 2
names = nameof(x, y) # names == ('x', 'y')
# Detect next attribute access
class MyClass:
def method(self):
next_attr = will()
return f"You'll access: {next_attr}"
obj = MyClass()
result = obj.method().some_attr # result == "You'll access: some_attr"
# Get argument names inside functions
def process(*args, **kwargs):
arg_names = argname('*args', 'kwargs')
return arg_names
a, b = 1, 2
result = process(a, b, c=3) # result == (('a', 'b'), {'c': 'c'})Varname uses Python's execution stack inspection and AST analysis to provide runtime name retrieval:
The ignore system allows precise frame targeting by filtering modules, functions, decorators, and qualified names.
Primary functions for retrieving variable names from function calls and getting names of variables passed as arguments.
def varname(
frame: int = 1,
ignore: IgnoreType = None,
multi_vars: bool = False,
raise_exc: bool = True,
strict: bool = True
) -> Union[str, Tuple[Union[str, Tuple], ...]]: ...
def nameof(
var: Any,
*more_vars: Any,
frame: int = 1,
vars_only: bool = True
) -> Union[str, Tuple[str, ...]]: ...Functions for detecting upcoming attribute access and retrieving argument names passed to functions.
def will(frame: int = 1, raise_exc: bool = True) -> str: ...
def argname(
arg: str,
*more_args: str,
func: Callable = None,
dispatch: Type = None,
frame: int = 1,
ignore: IgnoreType = None,
vars_only: bool = True
) -> Union[ArgSourceType, Tuple[ArgSourceType, ...]]: ...Utility functions and classes that build upon the core functionality for common use cases.
from varname.helpers import register, Wrapper, jsobj, debug, exec_codedef register(
cls_or_func: type = None,
frame: int = 1,
ignore: IgnoreType = None,
multi_vars: bool = False,
raise_exc: bool = True,
strict: bool = True
) -> Union[Type, Callable]: ...
class Wrapper:
def __init__(
self,
value: Any,
frame: int = 1,
ignore: IgnoreType = None,
raise_exc: bool = True,
strict: bool = True
): ...
def debug(
var,
*more_vars,
prefix: str = "DEBUG: ",
merge: bool = False,
repr: bool = True,
sep: str = "=",
vars_only: bool = False
) -> None: ...
def jsobj(
*args: Any,
vars_only: bool = True,
frame: int = 1,
**kwargs: Any
) -> Dict[str, Any]: ...
def exec_code(
code: str,
globals: Dict[str, Any] = None,
locals: Dict[str, Any] = None,
/,
sourcefile: PathLike | str = None,
frame: int = 1,
ignore: IgnoreType = None,
**kwargs: Any
) -> None: ...Configuration options and comprehensive exception hierarchy for error handling.
class config:
debug: bool = False
class VarnameException(Exception): ...
class VarnameRetrievingError(VarnameException): ...
class ImproperUseError(VarnameException): ...
class QualnameNonUniqueError(VarnameException): ...
class VarnameWarning(Warning): ...
class MultiTargetAssignmentWarning(VarnameWarning): ...
class MaybeDecoratedFunctionWarning(VarnameWarning): ...
class UsingExecWarning(VarnameWarning): ...from typing import Union, List, Tuple, Callable, Dict, Any, Mapping, Optional
from types import ModuleType, FunctionType
from pathlib import Path
import ast
from os import PathLike
# Ignore system types
IgnoreElemType = Union[
ModuleType,
str,
Path,
FunctionType,
Tuple[Union[ModuleType, str], str],
Tuple[FunctionType, int]
]
IgnoreType = Union[IgnoreElemType, List[IgnoreElemType]]
# Argument source types (progressive type definition)
ArgSourceType = Union[ast.AST, str]
ArgSourceType = Union[ArgSourceType, Tuple[ArgSourceType, ...]]
ArgSourceType = Union[ArgSourceType, Mapping[str, ArgSourceType]]