Flying With Python (Strong versus Weak Typing)
Gerhard Häring
gerhard.haering at opus-gmbh.net
Tue Mar 11 09:15:22 EST 2003
Chermside, Michael <mchermside at ingdirect.com> wrote:
> Hasoob ahs writes:
>> I would like to hear from other Python programmers [whether they'd fly in
>> a python-controlled airplane].
>> Would you be comfortable?. Your answer may help me decide between
>> strong and weak typing. I prefer an answer of yes or no followed by an
>> explanation.
>
> Hasoob, I hope the following helps answer your question.
>
> I prefer (I think) strong (ie, explicit) typing.
>
> I'm a BIG Python fan.
>
> The reason that I prefer strong typing is that I tend to think about
> the type of the object that I pass around. I like to have the compiler
> know what types I'm using because it's something that _I_ as the
> programmer knows. In a way, it's kind of like python's use of
> indentation... since the programmer uses indentation (even in Java or
> C), the compiler should also!
>
> HOWEVER, after working with Python for a time, I have learned that
> there are a few major DRAWBACKS to strong typing (as usually
> implemented), and that the ADVANTAGES are far less than most believe.
>
> (1) The first drawback is FAR too much typing, particularly of redundant
> information! I don't mind the typing itself, but the huge amount of
> text needed to declare every type every place can obscure the actual
> code (and easier-to-read code is better code!). Consider these:
>
> // Java example
> public int countBlueWidgets(List widgets, int min, int max) {
> Iterator iter = widgets.iterator();
> int i = 0;
> while (iter.hasNext() && i < min) {
> i++;
> iter.next();
> }
> int count = 0;
> while (iter.hasNext() && i < max) {
> i++;
> Widget w = (Widget) iter.next();
> if (w.isBlue()) {
> count++;
> }
> }
> return count;
> }
>
>
> # Example in Python
> # assumes java-style iterator for consistency (perhaps it's in jython?)
> def countBlueWidgets(widgets, min, max):
> iter = widgets.iterator()
> i = 0
> while iter.hasNext() and i < min:
> i += 1
> count = 0
> while iter.hasNext() and i < min:
> i += 1
> w = iter.next()
> if w.isBlue():
> count += 1
> return count
Or even:
def countBlueWidgets(widgets, min, max):
count = 0
for w in widgets[min:max]:
if w.isBlue():
count += 1
return count
*Way* clearer IMO. And all because Python supports slicing in the language
instead.
Btw. my pet-peeve in Java is the lack of Ada-like generics, so that in order to
avoid casting like hell as you did above, you have to implement your own
iterator class for each time.
-- Gerhard
More information about the Python-list
mailing list