declaration of variables?
Mike Meyer
mwm at mired.org
Mon Feb 17 17:16:45 EST 2003
mwilson at the-wire.com (Mel Wilson) writes:
> My favorite poster child for not declaring things is:
I can't resist...
> def number (s):
> "convert something (probably a string) to a convenient numeric type"
> try:
> return int (s)
> except ValueError:
> try:
> return long (s)
> except ValueError:
> return float (s)
>
> If I had to declare things, I'd have to declare the
> return type of `number`, and obviously I don't want to.
With a sane strict type system, you declare it as "number", a deferred
class of which int, long and float are subclasses.
> Since the parameter `s` has no declared type, `number` is
> safe to call with an object that's already a number, and it
> can be called successfully with any class instance that has
> a __int__, __long__ or __float__ method,
s, on the other hand, is harder to deal with, because you're relying
on the ability to dynamically test for a method, which is something
relatively rare in strictly typed languages.
BTW, I'd have added one more try-except clause, so that "j" would be
correctly converted to a complex :-).
<mike
--
Mike Meyer <mwm at mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
More information about the Python-list
mailing list