[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [pygame] Problems with getting keyboard input. [identity vsequality]





On Tue, 25 Jun 2002, Jonathan Atkinson wrote:

> Thanks, that's helped. I guess it's a syntactical thing then: what use
> does 'is' serve? I assumed it was directly equivalent to '==', but it
> looks like I was wrong. Secondly, why does using 'is' work with K_ESCAPE
> and K_SPACE but not with K_UP?

All things in Python are objects, even integers.  When we want to check if
two objects are equal, we should use '==', but if we want to see if
they're the same object --- identical --- then we should use 'is' instead.


The difference is somewhat subtle, but here's an example with lists that
might clear it up:

###
>>> mylist1 = [3, 1, 4, 1, 5, 9]
>>> mylist2 = [3, 1, 4, 1, 5, 9]
>>> mylist1 == mylist2
1
>>> mylist1 is mylist2
0
###

'mylist1' and 'mylist2' are distinct lists, so the 'is' check says that
they're not identical, even though they're "equal".  But now let's try
something else:

###
>>> mylist3 = mylist2
>>> mylist2 == mylist3
1
>>> mylist2 is mylist3
1
###

Here, 'is' tells us that mylist2 and mylist3 are naming the same list.
This is significant because if we make changes to the object named by
mylist2, we'll see that "change" in mylist3, but only because they both
name the same object:

###
>>> mylist2.append(2)
>>> mylist1
[3, 1, 4, 1, 5, 9]
>>> mylist2
[3, 1, 4, 1, 5, 9, 2]
>>> mylist3
[3, 1, 4, 1, 5, 9, 2]
###




Going to your question, K_UP is a numerical code for 273:

###
>>> pygame.locals.K_UP
273
###

and if we're curious, we can also lookup the values of K_SPACE and
K_ESCAPE:

###
>>> pygame.locals.K_SPACE
32
>>> pygame.locals.K_ESCAPE
27
###

There's one main difference between K_UP and the other two constants, and
it's a silly-but-significant observation: K_UP is larger than the other
two numbers!


It turns out that all numbers that are less than around 100 are cached by
Python, so that there's only one copy of each small number throughout the
Python system.  This allows 'is' to work perfectly well on small integers,
but not on larger values:

###
>>> 90 is 89 + 1
1
>>> 273 == 272+1
1
>>> 273 is 272+1
0
###




> It seems a little illogical, unless I'm missing something.

It's not illogical; it's just that I think 'is' is not the right
comparison operation in almost all cases.


Hope this helps!

____________________________________
pygame mailing list
pygame-users@seul.org
http://pygame.seul.org