detecting containers during object introspection

David C. Fox davidcfox at post.harvard.edu
Mon Jul 21 13:27:57 EDT 2003


Is there a reasonable way to tell whether a variable is a container 
(either a mapping or a sequence) and whether it is a mapping or a 
sequence?  [For background on why I'm asking this question, see the end 
of the message]

isMappingType and isSequenceType in the operator module return true for 
any class instance.  The documentation for those functions says 
(correctly) that there is no general way to tell whether a class 
supports the complete mapping or sequence interfaces, but still, it 
would be nice to be able to tell whether

for elem in x:

would fail or succeed, without relying on something like isinstance(x, 
list), which would fail for a tuple or a UserList, or any other custom 
class.  Is calling iter(x) and catching the possible TypeError the 
closest I can get?  And what would be the closest equivalent for mapping 
types.

Wouldn't it be helpful to have an abstract base class Sequence which 
didn't add any actual attributes or methods, but which someone writing a 
sequence class could include as a base class, as a sort of unenforced 
promise that the sequence operators were supported?

Thanks in advance for any suggestions,
David

---


Why am I asking this question?

I'm trying to write a regression test for a class which pickles 
dictionaries of attributes to store and retrieve instances.  The 
dictionary includes a version number, and the class has a system for 
updating out-of-date instances to the current version.

As part of the test, I need to be able to compare the structure of the 
two dictionaries to see if the developer has modified their structure 
but forgotten to increment the current version.  Values in the 
dictionary may be unknown objects, in which case I just want to compare 
their types.  However, the values may also be sequences or mappings 
themselves, in which case I want to recursively compare their 
elements/values.






More information about the Python-list mailing list