r/Python • • Jun 23 '14

Writing better python code

https://gist.github.com/kracekumar/09a60ec75a4de19b346e
143 Upvotes

126 comments sorted by

View all comments

12

u/steve_no Jun 23 '14

The normal code "is" example seems strange. I think the non-pythonic thing most programmers do with respect to "is" is not using it, for example:

if a == None:

when they should be doing:

if a is None:

10

u/erewok Jun 23 '14 edited Jun 23 '14

Correct me if I'm wrong here, but I thought:

if a is None...

Is asking if a and None (the singleton value) point to the same memory space. It's not asking if they're equivalent; it's asking if they are the same actual thing.

Thus, is is not the same as equivalence how we usually think of it (double equals).

That's why setting a default value of None is so useful in function definitions: there's only one None and your function value either is that thing or it's not. It's never going to be like None enough to pass for it.

5

u/fuzz3289 Jun 23 '14

You sir are correct. Though "memory location" isnt a great way to say it. I would say:

The is operator returns true if both names are bound to the same object instance.

Since the "names" wont share a memory location.

3

u/erewok Jun 23 '14

Funny enough, I was curious about how the Python built-in callable was implemented just now and I stumbled on this page with the following quote:

Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The ‘is‘ operator compares the identity of two objects; the id() function returns an integer representing its identity.

3

u/fuzz3289 Jun 23 '14

"You may think of it as" is important. The identity is actual a hash of the name in a lookup table.

Not to argue or anything, just want to emphasize that you cant actually deal with memory or memory locations directly in python.

1

u/rcxdude Jun 24 '14

Actually, the identity in Cpython is just the memory address of the object (literally casting the pointer to an int). It doesn't have to be according to the language though.

1

u/fuzz3289 Jun 24 '14

https://docs.python.org/3.3/reference/datamodel.html

Interesting, I didn't realize that it was just a direct address. Thanks for the correction.