does lack of type declarations make Python unsafe?

Alex Martelli aleax at
Tue Jun 17 10:15:27 CEST 2003

Bengt Richter wrote:
>>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

Yes.  The solution I suggested then (and keep in my sleeve for possible
future needs, but have never needed yet -- see below) was

    try: s[:0]+''

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

You cannot "feel sure" in any language that allows "virtual methods":
whenever you call a potentially-virtual method you _might_ be hitting
a weird override that has crazy side effects.  To achieve polymorphism,
you give up on the yearning to "feel sure" and trust the client to NOT
do such crazy things.  Testing candidate args is not any different from
using any (potentially virtual) operation whatsoever on the args, i.e.,
no different from any other application whatsoever of polymorphism.

> 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 '' ?

I prefer the more concise suggestion above, which requires slicing
instead of indexing and logical tests.  However, the issues are
similar.  In particular, both of these tests classify mmap.mmap
instances as "string-like", while my preferred s+'' doesn't -- i.e.,
an mmap instance isn't "directly" string-like, but its slices and
items are (indeed, said slices and items ARE strings!-).  So, in
my sleeve next to the slicing possibility is a small reminder to
specialcase mmap if I ever do end up needing that... and, the very
need to specialcase is in turn a reminder that the workarounds are
not entirely pleasant.


More information about the Python-list mailing list