File tree Expand file tree Collapse file tree 1 file changed +19
-9
lines changed
Expand file tree Collapse file tree 1 file changed +19
-9
lines changed Original file line number Diff line number Diff line change @@ -40,10 +40,10 @@ allowing for easier refactoring.
4040In 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
4949It works for class attributes and instance variables.
@@ -54,14 +54,11 @@ class Bar:
5454bar = Bar()
5555print (nameof(Bar.attr)) # Output: 'attr'
5656print (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
6562class Inner :
6663 @ property
6764 def value (self ):
@@ -75,6 +72,19 @@ outer = Outer()
7572print (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
8090If you pass a value or an expression that is not a variable or attribute, ` nameof ` raises a ` ValueError ` :
You can’t perform that action at this time.
0 commit comments