testing type of an object

Mark McEahern marklists at mceahern.com
Fri Jun 28 15:12:17 EDT 2002


> Hi,
>   I'm writing some code that depends on the type of an argument
> passed to it.

In general, this is a sign that you are using Python to program in the
paradigms of some other language.  There are exceptions, of course.  And I'm
sadly not astute enough to be able to summarize them for you.  ;-)

Anyway...

> Is there a standard trick to do this? My versions don't seem to work:
>
> if type(s) == 'str':
>   do something

Suppose s is:

  s = "foo"

You can test whether it's a string like this:

  if type(s) == type("any known string")

substituting your favorite curse word or aphorism for "any known string".

Here's why this approach is bad, by the way:

class myString(str):

  def __init__(self, s):
    self.s = s
  def __str__(self):
    return self.s

This myString can quickly be made to substitute for a string.  But your code
that does strong type checking won't allow it.

In other words, testing the type of something or whether it's
isinstance(whatever), doesn't tell you whether it walks like a duck and
quacks like a duck.  In general, Python encourages you to care how things
walk and talk not what "type" of thing they are.

Of course, your specific problem may require you to engage in the kind of
bondage you asked about.  ymmv.

Cheers,

// mark

-






More information about the Python-list mailing list