does lack of type declarations make Python unsafe?

Alex Martelli aleax at
Mon Jun 16 10:54:23 CEST 2003

<posted & mailed>

martin z wrote:

>> You *can* test the types of the arguments yourself, inside
>> the function. But this is regarded bad practice amongst Python
>> programmers, for the above mentioned reasons.
> On this subject, is there a way to test not the specific type, or simply
> the
> protocol an object supports?  String, int, etc.  I want to make a function
> do one thing with a numeric-type object and a different thing with a
> string-type object.

It depends, of course, on what you want "numeric-type" and "string-type"
to mean.  For my purposes, I've found the following very simple "protocol
testing" functions work just fine:

def isStringLike(s):
    try: s+''
    except: return False
    else: return True

def isNumberLike(s):
    try: s+0
    except: return False
    else: return True

I haven't actually used the second one very often; perhaps it might
give problems with e.g. "number-vector" types that let you perform
SOME number-like operations (such as "add a scalar to each item") but
not others.  The first one I use regularly and still find preferable
to e.g. "isinstance(s, basestring)" which doesn't classify as "string
like" such obvious cases as instances of UserString.UserString.

Of course, this overall approach does depend on an underlying
assumption that types are defined "sensibly" -- e.g. that if a type
is string-like enough to let you concatenate its instances to a
string, then it will also be string-like enough from other points
of view.  I have not found that to be a problem in practice.


More information about the Python-list mailing list