eval function not working how i want it dag namn

Michael Hoffman cam.ac.uk at mh391.invalid
Fri Apr 15 11:09:27 EDT 2005


robcarlton wrote:

> I've written this function to make a list of all of an objects
> attributes and methods (not for any reason, I'm just learning)
> 
> def list_members(obj)
>     l = dir(obj)
>     return map(lambda x : eval('obj.'+x), l)

That works fine for me with Python 2.4.

This is the best way to do it:

def list_members(obj):
     return [getattr(obj, name) for name in dir(obj)]

Although personally I would prefer to have this information in dict 
form, so i'd use:

return dict((name, getattr(obj, name)) for name in dir(obj))

For objects defined in CPython, you can use obj.__dict__, but this is 
somewhat hacky, and I'd avoid it.
-- 
Michael Hoffman



More information about the Python-list mailing list