Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, Evaluate a Variable value as a Variable

Tags:

python

I'd like to do something like below: particularly the 'f.eval(field)' part, such that it evaluates the value of the variable as the field name. How does one accomplish this in Python?

def punctuated_object_list(objects, field):
    field_list = [f.eval(field) for f in objects]
    if len(field_list) > 0:
        if len(field_list) == 1:
            return field_list[0]
        else:
            return ', '.join(field_list[:-1]) + ' & ' + field_list[-1]
    else:
        return u''
like image 293
Antonius Common Avatar asked Mar 11 '09 00:03

Antonius Common


1 Answers

getattr(f, field), if I understand you correctly (that is, if you might have field = "foo", and want f.foo). If not, you might want to clarify. Python has an eval(), and I don't know what other languages' eval() you want the equivalent of.

like image 50
Devin Jeanpierre Avatar answered Oct 16 '22 19:10

Devin Jeanpierre