Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classes nested in functions and attribute lookup

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?

like image 204
nkrkv Avatar asked Dec 22 '22 10:12

nkrkv


2 Answers

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.

like image 185
Nick Dandoulakis Avatar answered Jan 07 '23 04:01

Nick Dandoulakis


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.

like image 42
Daniel Roseman Avatar answered Jan 07 '23 04:01

Daniel Roseman