Python NameError when var IS most definitely defined

一个人想着一个人 提交于 2019-12-01 11:09:28

Mysterious NameErrors may arise from your file containing invisible control characters. On unix machines, you can spot these errors by looking at the output of

cat -A filename.py

Try to print file_name after each line, to see if somebody is removing the "file_name" variable from your namespace.

In addition, to be more pythonic (and efficient), use

file_name = "_".join((self.client_id, self.client_name, self.batch_num))

to concatenate strings.

If you're assigning file_name here:

file_name = self.client_id+"_"+self.client_name+"_"+self.batch_num

And you're getting a NameError reporting, that file_name is not defined, then try wrapping the operation in a try..except, to see what is going wrong:

try:
    file_name = self.client_id+"_"+self.client_name+"_"+self.batch_num
except NameError as err:
    print err, 'failed, here is some debug stuff:'
    print "CLIENT ID   =", self.client_id
    print "CLIENT NAME =", self.client_name
    print "BATCH NUM   =", self.batch_num

If any of this is failing, this will set you on the course to finding out why and narrowing down the cause of it.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!