I have the following simplified code:
scope = locals()
for batch in stream:
for row in batch.results:
writer.writerow([eval(pf, scope) for pf in process_fields])
It saves in a csv the content of the different fields of the row object (GoogleAdsRow object)
It works fine, but it fails if I do not use scope variable, but locals() function directly:
for batch in stream:
for row in batch.results:
writer.writerow([eval(pf, locals()) for pf in process_fields])
It returns:
NameError: name 'account' is not defined where account is one of the process_fields.
So I assume it's because the eval function do not find the variable, but I do not understand why such an small change create that issue.
CodePudding user response:
It's not a small change. In the code you show, there are two scopes:
- Whatever scope the loop is in.
- The scope created by the list comprehension.
In your first example, you call locals in the first scope.
In your second example, you call locals in the second scope.
