0
# Varname
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: varname
7
- **Language**: Python
8
- **Installation**: `pip install varname`
9
- **Python Version**: 3.8+
10
11
## Core Imports
12
13
```python
14
from varname import varname, nameof, will, argname
15
```
16
17
Importing exceptions, configuration, and version info:
18
19
```python
20
from varname import (
21
VarnameException,
22
VarnameRetrievingError,
23
ImproperUseError,
24
config,
25
__version__
26
)
27
```
28
29
Importing helper functions:
30
31
```python
32
from varname.helpers import register, Wrapper, jsobj, debug, exec_code
33
```
34
35
Importing ignore system classes:
36
37
```python
38
from varname.ignore import IgnoreModule, IgnoreFunction, IgnoreList
39
```
40
41
### Package Version
42
43
```python { .api }
44
__version__: str = "0.15.0"
45
```
46
47
## Basic Usage
48
49
```python
50
from varname import varname, nameof, will, argname
51
52
# Get variable name from function assignment
53
def create_data():
54
return varname()
55
56
my_data = create_data() # my_data == 'my_data'
57
58
# Get names of variables passed to function
59
x = 1
60
y = 2
61
names = nameof(x, y) # names == ('x', 'y')
62
63
# Detect next attribute access
64
class MyClass:
65
def method(self):
66
next_attr = will()
67
return f"You'll access: {next_attr}"
68
69
obj = MyClass()
70
result = obj.method().some_attr # result == "You'll access: some_attr"
71
72
# Get argument names inside functions
73
def process(*args, **kwargs):
74
arg_names = argname('*args', 'kwargs')
75
return arg_names
76
77
a, b = 1, 2
78
result = process(a, b, c=3) # result == (('a', 'b'), {'c': 'c'})
79
```
80
81
## Architecture
82
83
Varname uses Python's execution stack inspection and AST analysis to provide runtime name retrieval:
84
85
- **Executing Library**: Core dependency for reliable AST node retrieval from stack frames
86
- **Frame Ignoring System**: Sophisticated filtering to skip intermediate decorator and library frames
87
- **AST Analysis**: Direct parsing of abstract syntax trees to extract variable and function names
88
- **Bytecode Fallback**: Alternative name retrieval when source code is unavailable (REPL, exec environments)
89
90
The ignore system allows precise frame targeting by filtering modules, functions, decorators, and qualified names.
91
92
## Capabilities
93
94
### Core Variable Name Retrieval
95
96
Primary functions for retrieving variable names from function calls and getting names of variables passed as arguments.
97
98
```python { .api }
99
def varname(
100
frame: int = 1,
101
ignore: IgnoreType = None,
102
multi_vars: bool = False,
103
raise_exc: bool = True,
104
strict: bool = True
105
) -> Union[str, Tuple[Union[str, Tuple], ...]]: ...
106
107
def nameof(
108
var: Any,
109
*more_vars: Any,
110
frame: int = 1,
111
vars_only: bool = True
112
) -> Union[str, Tuple[str, ...]]: ...
113
```
114
115
[Core Functions](./core-functions.md)
116
117
### Attribute Detection and Argument Inspection
118
119
Functions for detecting upcoming attribute access and retrieving argument names passed to functions.
120
121
```python { .api }
122
def will(frame: int = 1, raise_exc: bool = True) -> str: ...
123
124
def argname(
125
arg: str,
126
*more_args: str,
127
func: Callable = None,
128
dispatch: Type = None,
129
frame: int = 1,
130
ignore: IgnoreType = None,
131
vars_only: bool = True
132
) -> Union[ArgSourceType, Tuple[ArgSourceType, ...]]: ...
133
```
134
135
[Advanced Functions](./advanced-functions.md)
136
137
### Helper Functions and Classes
138
139
Utility functions and classes that build upon the core functionality for common use cases.
140
141
```python
142
from varname.helpers import register, Wrapper, jsobj, debug, exec_code
143
```
144
145
```python { .api }
146
def register(
147
cls_or_func: type = None,
148
frame: int = 1,
149
ignore: IgnoreType = None,
150
multi_vars: bool = False,
151
raise_exc: bool = True,
152
strict: bool = True
153
) -> Union[Type, Callable]: ...
154
155
class Wrapper:
156
def __init__(
157
self,
158
value: Any,
159
frame: int = 1,
160
ignore: IgnoreType = None,
161
raise_exc: bool = True,
162
strict: bool = True
163
): ...
164
165
def debug(
166
var,
167
*more_vars,
168
prefix: str = "DEBUG: ",
169
merge: bool = False,
170
repr: bool = True,
171
sep: str = "=",
172
vars_only: bool = False
173
) -> None: ...
174
175
def jsobj(
176
*args: Any,
177
vars_only: bool = True,
178
frame: int = 1,
179
**kwargs: Any
180
) -> Dict[str, Any]: ...
181
182
def exec_code(
183
code: str,
184
globals: Dict[str, Any] = None,
185
locals: Dict[str, Any] = None,
186
/,
187
sourcefile: PathLike | str = None,
188
frame: int = 1,
189
ignore: IgnoreType = None,
190
**kwargs: Any
191
) -> None: ...
192
```
193
194
[Helper Functions](./helper-functions.md)
195
196
### Configuration and Error Handling
197
198
Configuration options and comprehensive exception hierarchy for error handling.
199
200
```python { .api }
201
class config:
202
debug: bool = False
203
204
class VarnameException(Exception): ...
205
class VarnameRetrievingError(VarnameException): ...
206
class ImproperUseError(VarnameException): ...
207
class QualnameNonUniqueError(VarnameException): ...
208
209
class VarnameWarning(Warning): ...
210
class MultiTargetAssignmentWarning(VarnameWarning): ...
211
class MaybeDecoratedFunctionWarning(VarnameWarning): ...
212
class UsingExecWarning(VarnameWarning): ...
213
```
214
215
[Configuration and Exceptions](./config-exceptions.md)
216
217
## Type Definitions
218
219
```python { .api }
220
from typing import Union, List, Tuple, Callable, Dict, Any, Mapping, Optional
221
from types import ModuleType, FunctionType
222
from pathlib import Path
223
import ast
224
from os import PathLike
225
226
# Ignore system types
227
IgnoreElemType = Union[
228
ModuleType,
229
str,
230
Path,
231
FunctionType,
232
Tuple[Union[ModuleType, str], str],
233
Tuple[FunctionType, int]
234
]
235
IgnoreType = Union[IgnoreElemType, List[IgnoreElemType]]
236
237
# Argument source types (progressive type definition)
238
ArgSourceType = Union[ast.AST, str]
239
ArgSourceType = Union[ArgSourceType, Tuple[ArgSourceType, ...]]
240
ArgSourceType = Union[ArgSourceType, Mapping[str, ArgSourceType]]
241
```