0

My code is similar like this:

class NN(object):


    def __init__(self,config=None,opts=None):
        self.file_vars   = ['self.corpusfile','self.dbfile']
        self.corpusfile="data.json"
        self.dbfile="db.json"

    def saveNet(self):
        for name in self.file_vars:
            print(name)
            print(eval(name))
        b=dict( [(name,eval(name)) for name in self.file_vars])



a=NN()
a.saveNet()

the result is :

self.corpusfile
data.json
self.dbfile
db.json

error message is:

NameError: name 'self' is not defined

how to solve this problem?

Barmar
  • 741,623
  • 53
  • 500
  • 612
andy
  • 1,951
  • 5
  • 16
  • 30

1 Answers1

3

The list comprehension has its own local variable scope. eval can't see self, because self comes from an outer scope, and nothing triggers the closure variable mechanism that would be necessary for eval to see the variable. (The self reference in self.file_vars doesn't trigger it, because that expression is evaluated outside the list comprehension's scope, despite being part of the list comprehension.)

Stop using eval. It's dangerous, almost always a bad idea, and completely unnecessary for something like this. Appropriate replacement tools might include getattr, self.__dict__, or something else, depending on what your full use case looks like.

user2357112
  • 260,549
  • 28
  • 431
  • 505