Skip to content

Commit 78cefb4

Browse files
committed
2 parents c5dfdb4 + 38839da commit 78cefb4

File tree

1 file changed

+19
-9
lines changed

1 file changed

+19
-9
lines changed

README.md

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,10 @@ allowing for easier refactoring.
4040
In the example below, refactoring the name of second_param will propagate to the printed message without having to manually do it.
4141

4242
```python
43-
def myFuncWithAmazingLogging(first_param: int, second_param: int):
43+
def myFuncWithAmazingLogging(first_param: int):
4444
valid_threshold = 10
45-
if second_param < 10:
46-
print(f"The parameter {nameof(second_param)} should be less than {valid_threshold}")
45+
if first_param < 10:
46+
print(f"The parameter {nameof(first_param)} should be less than {valid_threshold}")
4747
```
4848

4949
It works for class attributes and instance variables.
@@ -54,14 +54,11 @@ class Bar:
5454
bar = Bar()
5555
print(nameof(Bar.attr)) # Output: 'attr'
5656
print(nameof(bar.attr)) # Output: 'attr'
57+
```
5758

58-
class MyClass:
59-
def __init__(self):
60-
self.instance_var = 123
61-
62-
obj = MyClass()
63-
print(nameof(obj.instance_var)) # Output: 'instance_var'
59+
It works also for nested classes.
6460

61+
```python
6562
class Inner:
6663
@property
6764
def value(self):
@@ -75,6 +72,19 @@ outer = Outer()
7572
print(nameof(outer.inner.value)) # Output: 'value'
7673
```
7774

75+
## Multiple assignments
76+
77+
If a variable is assigned twice, only the first name is returned.
78+
79+
```python
80+
a = b = 1
81+
82+
nameof(a) # returns "a"
83+
nameof(b) # returns "b"
84+
85+
nameof(1) # raises ValueError (see next section below)
86+
```
87+
7888
## Error Handling
7989

8090
If you pass a value or an expression that is not a variable or attribute, `nameof` raises a `ValueError`:

0 commit comments

Comments
 (0)