easy question on parsing python: "is not None"

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Aug 6 18:13:50 EDT 2010


On Fri, 06 Aug 2010 17:20:30 +0000, Peter Pearson wrote:

> On Fri, 06 Aug 2010 15:37:04 +0200, Stefan Schwarzer wrote: [snip]
>> I can imagine a case where you might want to compare a string with
>> `is`:
>>
>>     FORWARD = "forward"
>>     BACKWARD = "backward"
[...]
>> Actually, I've never seen such a use, as far as I remember. What do
>> other people here think? Is the code above, which compares strings with
>> `is`, bad style, and if yes, why? How would you write the code instead?
> 
> Hey, that's a cute example, but . . . what a trap!  Is it possible to
> document the use-the-object-not-the-string requirement loudly enough
> that people won't get caught?

Nope. People don't read documentation :)

That's why I prefer to test for human-readable constants using equality, 
so if the caller prefers to call func(x, "forward") instead of func(x, 
FORWARD) it will still work.

Or I use

FOWARD = object()
BACKWARDS = object()

and force them to use my constants.



-- 
Steven



More information about the Python-list mailing list