On Wed, Sep 21, 2011 at 11:41:58AM -0700, Reid Price wrote:
> On Wed, Sep 21, 2011 at 10:58 AM, Ben Pfaff <[email protected]> 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?
_______________________________________________
dev mailing list
[email protected]
http://openvswitch.org/mailman/listinfo/dev

Reply via email to