Interesting behaviour of the assignment

Tim Peters tim.one at home.com
Sun Dec 31 15:38:53 EST 2000


[Moshe Zadka]
> Here's an example where I'd rather use "is" then "==":
>
> # module foo.py
> SPAM = 0
> EGGS = 1
>
> def eat(what):
> 	if what is SPAM:
> 		eat_spam()
> 	if what is EGGS:
> 		eat_eggs()
> 	raise FoodError()
>
> # user code:
> import foo
>
> foo.eat(foo.SPAM)
> foo.eat(foo.EGGS)
>
> The semantics are accurate here: foo.eat should not be passed 0.0,
> it should be passed only foo.SPAM or foo.EGGS, so a FoodError
> will alert the programmer to his bug sooner.

Yet because Python stores little ints uniquely, they will not get a
FoodError if they happen to pass in an int 0 or 1 however arrived at (e.g.,
foo.eat(int("0"))).

You can make this robust like so:

class FoodType:
    pass

SPAM = FoodType()
EGGS = FoodType()

Now "is" is bulletproof.  A stranger way:

SPAM = []
EGGS = []

Any mutable object type will do; any immutable object type may or may not
work today, and whichever obtains today may change in the next release.

god-is-one-because-god-is-immutable<wink>-ly y'rs  - tim





More information about the Python-list mailing list