Classes nested in functions and attribute lookups

The following works: Ok, that is, does not 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 not understand the reason for this behavior. Can someone explain?

+4
source share
3 answers

The arg property obscures the argument to the arg function (inner scope)

 def foo(arg): class Nested(object): arg = arg # you try to read the `arg` property which isn't initialized 


You will get the same error if you enter i = i in the interpreter window without initializing the variable i .

+5
source

If you try to assign a variable inside a function, Python assumes that the variable is local to that function. Therefore, trying to assign arg to the value of yourself, you implicitly declare it as a local variable.

+3
source

This is due to the Python review rules:

 def foo(arg): # (1) class Nested(object): arg = arg # (2) 

(2) defines a new name "arg" in the class namespace, which does not reflect the value of another "arg" in the external namespace (1).

However, (2) is not necessary and the following is true:

 def foo(arg): class Nested(object): def message(self): print arg return Nested() nested = foo('hello') nested.message() 

(prints hello )

+3
source

All Articles