Bitten by my C/Java experience
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue May 5 04:19:59 EDT 2015
On Tuesday 05 May 2015 08:02, BartC wrote:
> On 04/05/2015 16:20, Cecil Westerhof wrote:
>> Potential dangerous bug introduced by programming in Python as if it
>> was C/Java. :-(
>> I used:
>> ++tries
>> that has to be:
>> tries += 1
>
> I think I've come across that. It doesn't mind ++ so people are likely
> to be assume that increment works as in other languages.
>
> I guess it just means +(+(a)).
Correct.
> But in that case, what meaning does:
>
> a
>
> or
>
> a+b
>
> have in Python? If they were function calls: a() or (a+b)(), then that's
> clear enough. But a+b doesn't do anything!
Not so.
The first one just does a name lookup and then throws the result away. The
second one looks up names a and b, then adds them together, throwing away
the result.
Here is one use for the first idiom:
try:
bin
except NameError:
# No built-in bin function, perhaps our Python is too old?
def bin(num):
...
Here's a good use for the second:
def calculate(x):
x + 0 # Fails if x is not a number.
...
That's an example of duck-typing. It allows any argument which supports
addition with integers, e.g. x could be a number, or some kind of array or
vector which supports addition with a scalar.
> (I think I would have picked up "++" and "--" as special tokens even if
> increment/decrement ops weren't supported. Just because they would
> likely cause errors through misunderstanding.)
Just because C made a mistake, doesn't mean other languages have to
slavishly follow it.
--
Steven
More information about the Python-list
mailing list