On Wed, Sep 21, 2011 at 12:30 PM, Ben Pfaff <b...@nicira.com> wrote: > On Wed, Sep 21, 2011 at 11:41:58AM -0700, Reid Price wrote: > > On Wed, Sep 21, 2011 at 10:58 AM, Ben Pfaff <b...@nicira.com> wrote: > > > > > I wish there was a simple way to just test for "iterable" and > > > "mapping" types (is there?). Then we could get rid of a lot of ugly > > > tests for specific types, in favor of more general tests. > > > > > > > The standard way to determine iterables is with > > > > hasattr(obj, '__iter__') > > > > It's not the prettiest (and note behavior with strings/unicode), but it > > generally behaves as expected. > > There isn't a great way to determine whether something is a 'map' in > > general, as {}[key] and [][index] > > both use the __getitem__ method. In practice, it is fairly rare to see > > non-dict maps. > > The Python reference manual says: > It is also recommended that mappings provide the methods > keys(), values(), items(), has_key(), get(), clear(), > setdefault(), iterkeys(), itervalues(), iteritems(), pop(), > popitem(), copy(), and update() behaving similar to those for > Python's standard dictionary objects. > > That seems to distinguish in practice: > >>> hasattr({}, "iterkeys") > True > >>> hasattr([], "iterkeys") > False > Any comment on whether how (un)wise it might be to use this to > distinguish maps from simple sequences? >
I think it seems reasonably safe to rely upon one (or several) attributes to distinguish maps from sequences. I would recommend using keys and/or values. The others might suffice, but are mostly too specific (iter*), too general (pop, copy, clear, items), or possibly deprecated (has_key). -Reid
_______________________________________________ dev mailing list dev@openvswitch.org http://openvswitch.org/mailman/listinfo/dev