easy question on parsing python: "is not None"
Ethan Furman
ethan at stoneleaf.us
Fri Aug 6 15:34:24 EDT 2010
Stefan Schwarzer wrote:
> Hello Peter,
>
> On 2010-08-06 19:20, 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"
>>>
>>> ...
>>>
>>> def func(direction=FORWARD):
>>> if direction is FORWARD:
>>> ...
>>> elif direction is BACKWARD:
>>> ...
>>> else:
>>> ...
>>> [...]
>
>> Hey, that's a cute example,
>
> Thanks!
>
>> 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?
>
> That's a good question, actually that's the nagging problem
> I also have with the approach.
>
> In production code I might write
>
> # Use _these_ objects to indicate directions, not string
> # constants with the same value.
> FORWARD = "forward"
> BACKWARD = "backward"
>
> However, that won't help if people import the module and see
> the strings under "global data" and so assume they're "just
> strings". Moreover, if you have to write such a comment for
> every use of the idiom the conciseness of the approach
> vanishes.
>
> Another view at the matter would be to let clients of the
> module find out their mistake by unit tests. But of course
> that's somewhat doubtful as the intention should be to write
> robust instead of bug-inviting code.
>
> I wonder if there's a way to have both the "cuteness" of the
> string constants _and_ more robustness.
>
> Stefan
Instead of using 'is' use '=='. Maybe not as cute, but definitely more
robust!
~Ethan~
More information about the Python-list
mailing list