mrc
mrc

Reputation: 3153

Eval only works if I define scope outside of the call

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.

Upvotes: 0

Views: 107

Answers (1)

chepner
chepner

Reputation: 530940

It's not a small change. In the code you show, there are two scopes:

  1. Whatever scope the loop is in.
  2. 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.

Upvotes: 3

Related Questions