Why = = (and not just =)

Alex Martelli aleax at aleax.it
Sun Oct 19 17:13:11 EDT 2003


Joe Green wrote:

> Sorry, I cant help aking stupid questions:
> 
> I understand why we need = = in C, but why in Python (or Java),
> surely if you write
>  if a=b: pass # syntax error
> it could not possibly mean anything other than what I intended
> (which was of course if a = = b:) ?

Well, it's quite conceivable it might mean != or <= -- as typos:
they're perfectly POSSIBLE, though not quite as LIKELY as the
typo you specifically made.  One of Python's principles is: in
fact of ambiguity, resist the temptation to guess.

In PL/I, I remember, I could write...:

if if = then then then = else else else = if

the role of each word and punctuation was perfectly clear to
_the PL/I parser_ -- one '=' is equality, the other two are
assignment, one each of 'if' 'then' and 'else' are keywords
and the others are variable names...

Unfortunately humans aren't quite as smart, so allowing
ambiguous-to-humans constructs because they "could not
possibly mean anything other than" (whatever) turned out
to be terribly error-prone.

I believe just about all languages designed after PL/I
took stock of the lesson (pity that still today some
popular languages have roots in ones designed _before_
PL/I, such as Basic -- they may perpetuate some, though
probably not all, of these "ambiguity" mistakes).

In Python there are other excellent reasons why == is
needed to indicate equality testing in some cases, and
therefore it should be always used (rather than letting
you use = when context allegedly makes it unambiguous)
to avoid making Python a complicated, context-dependent
language.  For example,

foo(fee, fie=fum)

passes a keyword argument fie with the value fum, while

foo(fee, fie==fum)

pasees a second positional argument, a bool, which is
True if fie equals fum, otherwise False.


Alex





More information about the Python-list mailing list