R Claven
R Claven

Reputation: 1210

Is it possible to use a variable as code in python

Almost 20 yrs ago when I learned perl, I remember you could us a variable as code. I am not sure why this isnt working so I would love to know if "interpolating a variable can become code" in python.

for instance:

def count_usages():

    fields_ls = ['reporter', 'creator', 'assignee', 'duedate']

    counts = {}

    for field in fields_ls:
        null_crit = field + "__isnull=True"
        blank_crit = field + "__exact=''"

        counts[field] = Ticket.objects.exclude(null_crit).exclude(blank_crit).count()


    for key, value in counts.iteritems():
        print "## - for " + key + " we had " + value

At some level I think Python is "compiled" so I am guessing a runtime evaluation like this wont work but I'd love to know for sure.

Pls advise. Thank you!

Upvotes: 1

Views: 86

Answers (2)

Nizam Mohamed
Nizam Mohamed

Reputation: 9240

See it works this way;

name = "False"
if name:
  print(name)

Outputs 'False' because name is non-empty str so it evaluates to True.

if eval(name):
  print(name)
else:
  print('no')

Outputs 'no' because names content has been evaluated in the context of currnet globals and locals.

But assignments don't work winth eval because in Python assignment is not an expression and eval needs an expression.

This is an error with eval;

s = "name=True"
eval(s)

To execute statements in a string, you have to use exec.

s = "name=True"
exec(s)

Now name is defined to be of type bool with value True.

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599956

No, but you would never ever want to do this. Always use a dictionary.

for field in fields_ls:
    null_crit = {field + "__isnull": True}
    blank_crit = {field + "__exact": ''}

    counts[field] = Ticket.objects.exclude(**null_crit).exclude(**blank_crit).count()

(Python's refusal to do this has nothing to do with it being "compiled"; it is exactly as compiled as Perl.)

Upvotes: 6

Related Questions