Preferred way of determining type
aleaxit at yahoo.com
Fri May 18 05:43:23 EDT 2001
"Frank Mitchell" <frankm at bayarea.net> wrote in message
news:3B04B384.22E328DB at bayarea.net...
> Alex Martelli wrote:
> > http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52291
> > suggests a general approach to do without type testing when you
> > think you just can't do without it. Mostly, you don't even need
> > that much -- try/except most often suffices!-)
> Ick. I can see the potential for a lot of redundant code to test
> whether an argument is sufficiently "list-like" for a particular
> purpose, using that article's method. Yeah, maybe you don't always need
> full transactionality,
Right -- fortunately. Partial alteration of state is not
often an issue. Sometimes it IS, though, and the recipe
focuses on those "sometimes".
> but (for example) testing whether you've been
> handled a string or a sequence of strings is kinda annoying.
Basically because a string *IS* a sequence of strings, in
Python's model -- not a suitable "for example", since it's
anything but typical of most data.
In other words: testing whether you've been handled a
single (e.g.) complex, or a sequence of complex's, is
trivial, because a single complex is NOT a sequence
of anything. So, for example:
for x in myarg: break
except TypeError: myarg_is_a_sequence = 0
else: myarg_is_a_sequence = 1
will work easily to test if myarg is or isn't a sequence,
using the pragmatic definition "a sequence is whatever
I can iterate on".
But a string IS a sequence...
> What *I* really want is a simple predicate to test whether an object is
> "sequence-like", "mutable-sequence-like", "mapping-like", "string-like",
> etc. I don't care whether it's a true list, a UserList, or some random
> class that implements the correct "magic methods". Sort of like
> post-hoc interface implementation.
Unfortunately, a string IS "sequence-like"... often you do want to
treat it as a sequence (looping on its characters), but at least
as often you want to treat it as "a single value".
Presumably, you would test is_string BEFORE you test is_sequence
to account for this.
Problem is, that this doesn't cover the issue "exactly WHAT
string-like behavior do you need out of the object"? Is it
enough that it can be concatenated to a string, for example?
except TypeError: return 0
else: return 1
or do you need more, such as the ability to be used as the
LHS operand for a % formatting operator, or...?
The "protocol adaptation" PEP 246 (which I think would be a
great addition to Python) and the "interface" PEP 245 would
give the basic tools to specify WHAT, EXACTLY, "sequencelike"
(&c) may mean in various contexts -- "adaptable to protocol
X" or "compliant with interface Y" and so on. But the various
protocols and interfaces should still be pinned down, and
the transition might not be easy IMHO.
More information about the Python-list