5

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''
1
  • +1 with my thanks for asking this question before I needed to :) . Commented Jun 17, 2009 at 11:27

4 Answers 4

13

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 beat me by seconds :-) Bonus doc: docs.python.org/library/functions.html#getattr
Silly me... eval(eval()) in python... thanks for your answer!
4
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.

1 Comment

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.
1

The python equivalent of eval() is eval()

x = 9
eval("x*2")

will give you 18.

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

works too.

1 Comment

eval is evil! better not use it at all, there's always a better way
0

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'}

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.