Varname

0.15.1 · active · verified Thu Apr 16

Varname is a Python library that provides 'dark magics' to retrieve the names of variables, arguments, and expressions at runtime. It's currently at version 0.15.1, offering functions like `varname()`, `nameof()`, and `argname()` to simplify introspection and debugging. The library maintains an active release cadence, with recent updates focusing on improved expression parsing and Python version compatibility.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the core `varname()` functionality, including the enhanced subscript support introduced in v0.15.1, and basic usage of `nameof()` and `argname()`.

import varname

def func():
    # varname() retrieves the name of the variable it's assigned to.
    return varname()

x = 0
a = [object] * 5

# Before v0.15.1, this might raise ImproperUseError.
# Now, it correctly prints 'a[x + 1]' (which evaluates to a[1]).
a[x + 1] = func()
print(f"Value at a[1]: {a[1]}")

# Demonstrating other new subscript supports from v0.15.1
b = []
b.append(func())
print(f"Element in b: {b[0]}") # prints 'b.append(func())'

# Using nameof to get an argument's name
def process(my_arg):
    return varname.nameof(my_arg)

result = process(x)
print(f"Name of argument 'x': {result}")

# Using argname to get argument names within a function
def greet(name, message):
    return varname.argname('name', 'message')

arg_names = greet('Alice', 'Hello')
print(f"Argument names in greet: {arg_names}") # {'name': 'name', 'message': 'message'}

view raw JSON →