On Wed, 25 Apr 2012 13:49:24 -0700, Adam Skutt wrote:

> Though, maybe it's better to use a different keyword than 'is' though,
> due to the plain English
> connotations of the term; I like 'sameobj' personally, for whatever
> little it matters.  Really, I think taking away the 'is' operator
> altogether is better, so the only way to test identity is:
>     id(x) == id(y)

Four reasons why that's a bad idea:

1) The "is" operator is fast, because it can be implemented directly by 
the interpreter as a simple pointer comparison (or equivalent). The id() 
idiom is slow, because it involves two global lookups and an equality 
comparison. Inside a tight loop, that can make a big difference in speed.

2) The "is" operator always has the exact same semantics and cannot be 
overridden. The id() function can be monkey-patched.

3) The "is" idiom semantics is direct: "a is b" directly tests the thing 
you want to test, namely whether a is b. The id() idiom is indirect: 
"id(a) == id(b)" only indirectly tests whether a is b.

4) The id() idiom already breaks if you replace names a, b with 
expressions:

>>> id([1,2]) == id([3,4])
True



> Though I would prefer:
>     addr(x) == addr(y)

But that's absolutely wrong. id(x) returns an ID, not an address. It just 
happens that, as an accident of implementation, the CPython interpreter 
uses the object address as an ID, because objects can't move. That's not 
the case for all implementations. In Jython, objects can move and the 
address is not static, and so IDs are assigned on demand starting with 1:


steve@runes:~$ jython
Jython 2.5.1+ (Release_2_5_1, Aug 4 2010, 07:18:19)
[OpenJDK Client VM (Sun Microsystems Inc.)] on java1.6.0_18
Type "help", "copyright", "credits" or "license" for more information.
>>> id(42)
1
>>> id("Hello World!")
2
>>> id(None)
3


Other implementations may make other choices. I don't believe that the 
language even defines the id as a number, although I could be wrong about 
that.

Personally, I prefer the Jython approach, because it avoids those 
annoying questions like "How do I dereference the address of an 
object?" (answer: Python is not C, you can't do that), and IDs are 
globally unique and never reused for the lifetime of the process.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to