or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-functions.mdconfig-exceptions.mdcore-functions.mdhelper-functions.mdindex.md
tile.json

tessl/pypi-varname

Dark magics about variable names in python

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/varname@0.15.x

To install, run

npx @tessl/cli install tessl/pypi-varname@0.15.0

index.mddocs/

Varname

Dark 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.

Package Information

  • Package Name: varname
  • Language: Python
  • Installation: pip install varname
  • Python Version: 3.8+

Core Imports

from varname import varname, nameof, will, argname

Importing 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_code

Importing ignore system classes:

from varname.ignore import IgnoreModule, IgnoreFunction, IgnoreList

Package Version

__version__: str = "0.15.0"

Basic Usage

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'})

Architecture

Varname uses Python's execution stack inspection and AST analysis to provide runtime name retrieval:

  • Executing Library: Core dependency for reliable AST node retrieval from stack frames
  • Frame Ignoring System: Sophisticated filtering to skip intermediate decorator and library frames
  • AST Analysis: Direct parsing of abstract syntax trees to extract variable and function names
  • Bytecode Fallback: Alternative name retrieval when source code is unavailable (REPL, exec environments)

The ignore system allows precise frame targeting by filtering modules, functions, decorators, and qualified names.

Capabilities

Core Variable Name Retrieval

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, ...]]: ...

Core Functions

Attribute Detection and Argument Inspection

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, ...]]: ...

Advanced Functions

Helper Functions and Classes

Utility functions and classes that build upon the core functionality for common use cases.

from varname.helpers import register, Wrapper, jsobj, debug, exec_code
def 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: ...

Helper Functions

Configuration and Error Handling

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): ...

Configuration and Exceptions

Type Definitions

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]]