Search code examples
pythonexecevalselfnameerror

NameError: name 'self' is not defined IN EXEC/EVAL


I was coding something, and there was an error in one part. But I can't find why the error occurs.

Code (Sample; similar to the error part):

class Test:
def __init__(self,a=0):
    self.x = a
    self.l = [2**x for x in range(a)]  #<--- self.l = [1,2,4,8,16]
    self.base()

def base(self):
    expr = "self.l{0} = [self.l[x]+{0} for x in range(self.x)]" #<--- when i=4, self.l4 = [5,6,8,12,20]
    for i in range(self.x):
        exec(expr.format(i))

w = Test(5)
print(w.l4)

So I thought that I get this:

[5, 6, 8, 12, 20]

BUT,

File "D:/Documents and Settings/Desktop/py/py/test2.py", line 12, in <module>
  w = Test(5)
File "D:/Documents and Settings/Desktop/py/py/test2.py", line 5, in __init__
  self.base()
File "D:/Documents and Settings/Desktop/py/py/test2.py", line 10, in base
  exec(expr.format(i))
File "<string>", line 1, in <module>
File "<string>", line 1, in <listcomp>

NameError: name 'self' is not defined

(Sorry for bad English)


Solution

  • There's no need for eval or exec here.

    for i in range(self.x):
        setattr(self, "l{}".format(i), [self.l[x]+i for x in range(self.x)])
    

    Although I don't know why you want to do this; better to keep it as a list rather than dynamically set attributes.