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.
pip install varnameVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates the core `varname()` functionality, including the enhanced subscript support introduced in v0.15.1, and basic usage of `nameof()` and `argname()`.
Adjust code expecting only the root variable name for attribute chains. If the old behavior is strictly required, pin `varname<0.13.0`.
If you were on `0.14.0` and `nameof` was removed, upgrade to `varname>=0.15.0` to regain its functionality. If you were considering migrating from `nameof` due to the deprecation warning in `0.13.4`, note that it has been brought back.
Upgrade to `varname>=0.15.1` for enhanced subscript support that handles dynamic indexing and more complex expressions.
Avoid using `varname` in code executed via `exec()`. For such scenarios, use `varname.helpers.exec_code()` instead of the built-in `exec()` to ensure source code is available at runtime, which `varname` can then analyze.
Upgrade to `varname>=0.15.1` for better support of complex expressions. If upgrading is not an option, simplify the expression where `varname()` is called, or assign its result to a simple variable first.
Upgrade to `varname>=0.15.0` to restore `nameof` functionality, as it was re-introduced in this version. Alternatively, refactor your code to use `varname.argname()` which can often achieve similar results, or use `varname()` if appropriate.
For scenarios where `varname.varname()` struggles, consider using `varname.helpers.Wrapper` to explicitly associate a value with its variable name. Example: `from varname.helpers import Wrapper; a = Wrapper(''); mydict = {val.name: val.value for val in [a]}`.Ensure you are passing `code`, `globals` (e.g., `globals().copy()`), `locals` (e.g., `locals().copy()`) and any other specified arguments according to the current `varname` documentation. Avoid passing `sourcefile` unless explicitly required and documented for public API usage.