How to tell if function was passed a list or a string?

Ben Finney bignose+hates-spam at benfinney.id.au
Wed May 17 19:22:38 EDT 2006


Roy Smith <roy at panix.com> writes:

> Ben Finney <bignose+hates-spam at benfinney.id.au> wrote:
> > Currently there's no good duck-typing way to differentiate strings
> > from other sequences.
> 
> I suppose you could do something like:
> 
> try:
>    foo.isalpha
> except AttributeError:
>    print "foo is not a string"
> 
> but other than proving that you don't *have* to use isinstance(), I
> don't think that approach has much going for it.

Duck typing preserves one very important feature of Python: a class
doesn't have to *inherit from* type 'foo' to be a *substitute for*
type 'foo'. An 'isinstance' check will fail on objects that don't
inherit from the string types, but do implement the interface
adequately.

In this example, if an object 'x' implements the behaviour you're
going to use, but doesn't inherit from 'basestring', refusing it just
because 'isinstance(x, basestring)' is False would be the wrong
choice.

-- 
 \         "I planted some bird seed. A bird came up. Now I don't know |
  `\                               what to feed it."  -- Steven Wright |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list