does lack of type declarations make Python unsafe?

Bengt Richter bokr at
Mon Jun 16 22:12:17 CEST 2003

On Mon, 16 Jun 2003 08:54:23 GMT, Alex Martelli <aleax at> wrote:

><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+''
Nit: succeeding with this test could be expensive if s is e.g., a 100MB file image
(I think this has come up before in a discussion of such testing, but I forgot if
it was me ;-)
>    except: return False
>    else: return True
>def isNumberLike(s):
>    try: s+0
>    except: return False
>    else: return True

I like the concept of testing for comptible behavior, but I would want to
feel sure that there could be no unexpected side effects from testing any
candidate args.

I know you understand all these issues, but all readers of this might not
without a mention ;-)

>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.
I wonder if
    try: s and s[0]+'' or s+''
would serve as well, and protect against the big-s hit. Or is
there a sensible string-like thing that doesn't support logical
tests and indexing but does support adding '' ?

>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.

Bengt Richter

More information about the Python-list mailing list