The following works Ok, i.e. it doesn't give any errors:
def foo(arg):
class Nested(object):
x = arg
foo('hello')
But the following throws an exception:
def foo(arg):
class Nested(object):
arg = arg # note that names are the same
foo('hello')
Traceback:
Traceback (most recent call last):
File "test.py", line 6, in <module>
foo('hello')
File "test.py", line 3, in foo
class Nested(object):
File "test.py", line 4, in Nested
arg = arg
NameError: name 'arg' is not defined
I can't understand the reason of such behavior. Could anybody explain?
The arg
property shadows the arg
function argument (inner scoping)
def foo(arg):
class Nested(object):
arg = arg # you try to read the `arg` property which isn't initialized
You get the same error if you type i = i
in the interpreter window without having initialized the i
variable.
If you try and assign to a variable within a function, Python assumes that variable is local to that function. So by trying to assign arg to the value of itself, you are implicitly declaring it as a local variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With