How can I tell when a string is in fact a number?

Alex Martelli aleaxit at
Mon Nov 6 16:49:45 CET 2000

"Dale Strickland-Clark" <dale at> wrote in message
news:eehd0t8ocpghnrm2c89dekanhmovteaaj2 at
> Thomas Gagne <tgagne at> wrote:
> >Wouldn't it make better sense to return a boolean?  Is it possible to
> >the String class to include a method, isNumber, that returns true or
> 1 and 0 are Python's boolean values.

Python's "boolean" stuff follows the Silver Rule (not as
important as the Golden Rule, but still pretty precious):

"Be liberal in what you can accept, conservative in what you
generate, but never allow an error without a diagnostic".

"Conservative in what you generate": when Python must
'generate' Boolean values (comparisons and operator not),
it always generates 0 for false, 1 for true.  (Having a
special-purpose datatype just for that would be more
than 'conservative'... really "reactionary"!-).

"Liberal in what you can accept": just about _any_ Python
object can be used where Python 'accepts' a Boolean value
(if, while, and, or, not...): a few specific values are
designed as "false" (0-numbers, empty-sequences, ...),
all others are taken as "true".

"Never allow an error without a diagnostic": unknown
variables or functions, attempts to call a non-callable,
etc, are NOT taken as either 'true' or 'false' if
evaluated in any context where Python expects a Boolean
value -- rather, they raise appropriate exceptions and
this terminates the expectant context (up to the inner
try/except block that will handle that exception).  Of
course, this is just like for non-Boolean contexts:-).


More information about the Python-list mailing list