tags:

views:

754

answers:

4

Hi!

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''
+8  A: 

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.

Devin Jeanpierre
+1 beat me by seconds :-) Bonus doc: http://docs.python.org/library/functions.html#getattr
bobince
Silly me... eval(eval()) in python... thanks for your answer!
Antonius Common
sorry, you're more right!
Antonius Common
A: 

The python equivalent of eval() is eval()

x = 9
eval("x*2")

will give you 18.

v = "x"
eval(v+"*2")

works too.

MarkusQ
you're both right... I can't tick both though ;-(
Antonius Common
eval is evil! better not use it at all, there's always a better way
hasen j
A: 

To get at a list of all the fields in a Python object you can access its __dict__ property.

class Testing():
    def __init__(self):
        self.name = "Joe"
        self.age = 30

test = Testing()
print test.__dict__

results:

{'age': 30, 'name': 'Joe'}
Soviut
Not the same. The object might not even have such an easily accessible __dict__ (might have to do something like object.__getattribute__(foo, '__dict__') if the object is mean), and it might have a new __getattr__.
Devin Jeanpierre
+2  A: 
getattr( object, 'field' ) #note that field is a string

f = 'field_name'
#...
getattr( object, f )


#to get a list of fields in an object, you can use dir()
dir( object )

For more details, see: http://www.diveintopython.org/power_of_introspection/index.html

Don't use eval, even if the strings are safe in this particular case! Just don't get yourself used to it. If you're getting the string from the user it could be malicious code.

Murphy's law: if things can go wrong, they will.

hasen j
Who would insert the "malicious" code? Python is distributed as source. Why mess around trying to get eval to break when the code is available to change? eval is no less safe than all the rest of Python.
S.Lott
consider the case when the code is running on a server,
hasen j