or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

core-functions.mddocs/

0

# Core Functions

1

2

Primary functions for retrieving variable names from function calls and getting names of variables passed as arguments. These functions form the foundation of varname's capabilities.

3

4

## Capabilities

5

6

### Variable Name Retrieval

7

8

Gets the name of the variable(s) that a function call or class instantiation is assigned to from inside the function.

9

10

```python { .api }

11

def varname(

12

frame: int = 1,

13

ignore: IgnoreType = None,

14

multi_vars: bool = False,

15

raise_exc: bool = True,

16

strict: bool = True

17

) -> Union[str, Tuple[Union[str, Tuple], ...]]:

18

"""

19

Get the name of the variable(s) that assigned by function call or class instantiation.

20

21

Args:

22

frame: Nth frame used to retrieve the variable name. This means N-1

23

intermediate frames will be skipped. Note that frames matching

24

ignore will not be counted.

25

ignore: Frames to be ignored in order to reach the Nth frame. Can be:

26

- A module (or filename): calls from it and submodules ignored

27

- A function: direct function calls ignored

28

- Tuple of (function, int): decorated function with decorator count

29

- Tuple of (module/filename, qualname): qualified name matching

30

multi_vars: Whether allow multiple variables on left-hand side. If True,

31

returns tuple of variable names even for single variable.

32

raise_exc: Whether to raise exception if failed to retrieve ast node.

33

Note: does NOT suppress ImproperUseError exceptions.

34

strict: Whether to only return variable name if result is assigned

35

directly (e.g. a = func() rather than a = [func()]).

36

37

Returns:

38

Variable name as string, or None if raise_exc=False and retrieval failed.

39

Tuple or hierarchy of variable names when multi_vars=True.

40

41

Raises:

42

VarnameRetrievingError: When unable to retrieve ast node and raise_exc=True

43

ImproperUseError: When varname usage is improper (multiple vars with

44

multi_vars=False, non-direct assignment with strict=True)

45

MultiTargetAssignmentWarning: When multiple targets in assignment

46

(e.g. a = b = func())

47

"""

48

```

49

50

#### Usage Examples

51

52

```python

53

from varname import varname

54

55

# Basic usage

56

def create_object():

57

return varname()

58

59

my_object = create_object() # my_object == 'my_object'

60

61

# Multiple variables

62

def create_pair():

63

return varname(multi_vars=True)

64

65

a, b = create_pair() # ('a', 'b')

66

67

# With ignore - skip decorator frames

68

def logged(func):

69

def wrapper(*args, **kwargs):

70

name = varname(ignore=logged) # Skip the decorator frame

71

print(f"Creating {name}")

72

return func(*args, **kwargs)

73

return wrapper

74

75

@logged

76

def make_data():

77

return [1, 2, 3]

78

79

data = make_data() # Prints: Creating data

80

```

81

82

### Variable Name Inspection

83

84

Gets the names of variables passed as arguments to a function, supporting both single and multiple variable inspection.

85

86

```python { .api }

87

def nameof(

88

var: Any,

89

*more_vars: Any,

90

frame: int = 1,

91

vars_only: bool = True

92

) -> Union[str, Tuple[str, ...]]:

93

"""

94

Get the names of the variables passed in.

95

96

Args:

97

var: The variable to retrieve the name of

98

*more_vars: Other variables to retrieve the names of

99

frame: Frame where this function is called from wrapper. frame=1 means

100

no wrappers. Standard library calls are ignored.

101

vars_only: Whether only allow variables/attributes as arguments or any

102

expressions. If False, source expressions are returned.

103

104

Returns:

105

Name/source of variable if single argument passed.

106

Tuple of names/sources if multiple variables passed.

107

For attributes with vars_only=True, only attribute name returned.

108

For attributes with vars_only=False, full expression returned.

109

110

Raises:

111

VarnameRetrievingError: When callee's node cannot be retrieved or

112

trying to retrieve full name of non-attribute calls.

113

114

Note:

115

Works in environments where source code is available. In REPL/exec

116

environments, falls back to bytecode analysis with limitations:

117

- Only single variable supported

118

- No keyword arguments allowed

119

- No full attribute name support

120

"""

121

```

122

123

#### Usage Examples

124

125

```python

126

from varname import nameof

127

128

# Basic variable name retrieval

129

a = 1

130

name = nameof(a) # name == 'a'

131

132

# Multiple variables

133

b = 2

134

names = nameof(a, b) # names == ('a', 'b')

135

136

# Attribute access

137

class Data:

138

def __init__(self):

139

self.value = 42

140

141

obj = Data()

142

attr_name = nameof(obj.value, vars_only=True) # attr_name == 'value'

143

full_name = nameof(obj.value, vars_only=False) # full_name == 'obj.value'

144

145

# In function with frame adjustment

146

def process_variables(*vars):

147

return nameof(*vars, frame=2) # Skip one additional frame

148

149

def wrapper(*args):

150

return process_variables(*args)

151

152

x, y = 10, 20

153

result = wrapper(x, y) # result == ('x', 'y')

154

```