0

As mentioned on SE one can get all the iterable properties of an object with either dir(someObject) or someObject.__dict__. How does one get the non-iterable properties? Some libraries, such as Reqests, return objects with non-iterable properties.

2 Answers 2

2

It's impossible to list all attributes reliably in every circumstance, for the simple fact that attributes can be defined at runtime using __getattr__ or __getattribute__.

For example the following class has a 50% chance to create a new attribute or to raise an AttributeError.

import random class AttributeGenerator(object): def __getattr__(self, attr): if random.random() < 0.5: setattr(self, attr, None) return getattr(self, attr) else: raise AttributeError(attr) 

The only general-purpose functions to get attributes from an instance are dir() and vars().

Note that dir() by default combines the result obtained by __dict__, __slots__ and the class' __dict__ etc. Classes can redefine how dir() works on their instances by defining the __dir__ method, however I've never seen it used. If this method exists and "hides" some attributes for some reason you can simply do something like:

attributes = list(object.__dict__.keys()) + list(obj.__slots__) + list(type(obj).__dict__) 

(with the appropriate error checking!) in order to obtain the default's dir() output.


This said, if you are interested in a particular library then there might be some method specific for that library that works reliably.

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

Comments

1
import pprint from pprint pprint (vars(<object name>)) 

1 Comment

Thank you Monty. However, the non-iterable attributes are not exposed with vars().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.