Andy
Andy

Reputation: 10988

How can I get a list of attributes of a Python object which doen't have __dict__?

How would you do this for an instance of xml.etree.cElementTree.Element?

$ python
Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
>>> from xml.etree.cElementTree import Element 
>>> obj = Element('aaa')
>>> obj
<Element 'aaa' at 0x101bde270>
>>> dir(obj)
['__copy__', '__deepcopy__', '__reduce__', 'append', 'clear', 'extend', 'find', 'findall', 'findtext', 'get', 'getchildren', 'getiterator', 'insert', 'items', 'iter', 'iterfind', 'itertext', 'keys', 'makeelement', 'remove', 'set']
>>> obj.tag
'aaa'

Upvotes: 0

Views: 7845

Answers (2)

sye
sye

Reputation: 185

The xml.etree.ElementTree.Element object does have a __dict__.

>>> from xml.etree.ElementTree import Element  
>>> obj = Element('aaa')
>>> obj.__dict__
{'attrib': {}, 'tag': 'aaa', '_children': []}

The __dict__ is the dictionary of currently defined attributes. dir() calls __dir__(), which may be overrided.

Upvotes: 1

wRAR
wRAR

Reputation: 25693

If attributes are returned via custom __getattr__ or __getattribute__, you cannot know whether an attribute will be returned without trying and you cannot get a full list without trying all possible names. You can get the list of static attributes via dir().

Upvotes: 3

Related Questions