473,480 Members | 4,282 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Result of ``a is b''

Hello,

is there a rationale for the following behavior:
a = (1,2)
b = (1,2)
a is b False a = "12"
b = "12"
a is b

True

Thanks,
Axel
Jul 18 '05 #1
33 1741
"Axel Boldt" <ax*******@yahoo.com> wrote in message
news:40**************************@posting.google.c om...
is there a rationale for the following behavior:
>>> a = (1,2)
>>> b = (1,2)
>>> a is b False >>> a = "12"
>>> b = "12"
>>> a is b True


Probably an accident of implementation. Consider:
a = "1 2"
b = "1" + " 2"
a is b False

and, for that matter:
a = (1, 2)
b = a
a is b

True

Is there a reason that you care about this behavior?
Jul 18 '05 #2
Axel Boldt wrote:
is there a rationale for the following behavior:


Yes: It shouldn't matter to you what the implementation is doing.

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ I only regret that I have but one life to lose for my country.
-- Nathan Hale
Jul 18 '05 #3
> >>> a = (1,2)
>>> b = (1,2)
>>> a is b False >>> a = "12"
>>> b = "12"
>>> a is b True


Unless you care whether two names point to the same object, don't use
'is'. Instead compare for equality with '=='. That should work like
you want it to:
a = (1,2)
b = (1,2)
a == b True a = "12"
b = "12"
a == b

True

It will also handle the cases that Andrew points out.

- Josiah
Jul 18 '05 #4
On 15 Mar 2004 16:32:25 -0800, ax*******@yahoo.com (Axel Boldt) wrote:
is there a rationale for the following behavior:
>>> a = (1,2)
>>> b = (1,2)
>>> a is b False >>> a = "12"
>>> b = "12"
>>> a is b True


Here's another one:
x = 'akdijfkdienlskfi'
y = 'akdijfkdienlskfi'
x is y True x = 'a b'
y = 'a b'
x is y False x == y True


It has to do with how Python decides which strings to "internalize"
and make shared objects in order to save space. This is only a
problem with immutable objects. Others cannot be shared like this.

My suggestion is to *never* use 'is' with these objects unless you
really need the fact that it is faster than '==' and you test it
thoroughly for the kind of objects you will be comparing.

-- Dave

Jul 18 '05 #5

Axel> is there a rationale for the following behavior:
a = (1,2)
b = (1,2)
a is b False a = "12"
b = "12"
a is b

True

Sure. The "is" operator doesn't do an element-by-element comparison of the
two objects. It only compares the memory addresses of the two objects being
compared. The difference between the tuple case and the string case is that
string literals which look roughly like identifiers (no spaces, all letters,
digits or underscores) are automatically interned and are thus shared. As
Andrew Koenig indicated, it's an implementation detail. It improves
performance to intern identifiers and it's not worth the extra expense to
decide if a string literal is really being used as a variable name, so all
strings which look structurally like identifiers are interned. You should
generally only use "is" to compare objects against known singleton objects:
None, True, False and Ellipsis. Use "==" for everything else.

Skip

Jul 18 '05 #6
"David MacQuigg" <dm*@gain.com> wrote in message
news:gj********************************@4ax.com...
On 15 Mar 2004 16:32:25 -0800, ax*******@yahoo.com (Axel Boldt) wrote:
is there a rationale for the following behavior:
>>> a = (1,2)
>>> b = (1,2)
>>> a is b False
>>> a = "12"
>>> b = "12"
>>> a is b

True


Here's another one:
x = 'akdijfkdienlskfi'
y = 'akdijfkdienlskfi'
x is y True x = 'a b'
y = 'a b'
x is y False x == y True


It has to do with how Python decides which strings to "internalize"
and make shared objects in order to save space. This is only a
problem with immutable objects. Others cannot be shared like this.

My suggestion is to *never* use 'is' with these objects unless you
really need the fact that it is faster than '==' and you test it
thoroughly for the kind of objects you will be comparing.


I'd go a slightly different direction on this: "is" is for physical
identity, "==" is for semantic equivalence. Never mix the two.
You cannot guarantee physical identity across different releases
of CPython, let alone between CPython and Jython (Python on the
Java VM), IronPython (the experimental Python on the .Net CLR)
or PyPy (the even more experimental attempt to rewrite Python in
Python.) And I'm sure I've left out a couple of other environments.

Using "is" is appropriate in only two circumstances:

1) when you're checking if an object you created is bound to
an identifer that's under your control,

and

2) when you're checking one of the few objects that are guaranteed
by the Python specs to be singletons: None, True and False are the
standard suspects in this case.

John Roth


-- Dave

Jul 18 '05 #7
David MacQuigg <dm*@gain.com> wrote
x = 'akdijfkdienlskfi'
y = 'akdijfkdienlskfi'
x is y True x = 'a b'
y = 'a b'
x is y

False


Wow. So it seems that the action of "is" on immutables is unspecified
and implementation dependent, thus useless to the programmer.

Maybe one could redefine "is" on immutables as follows: for strings
and numbers it acts as "==", for tuples it acts as componentwise "is".
That would be a more useful operator IMHO.

Axel
Jul 18 '05 #8
Axel Boldt wrote:
David MacQuigg <dm*@gain.com> wrote

>x = 'akdijfkdienlskfi'
>y = 'akdijfkdienlskfi'
>x is y


True
>x = 'a b'
>y = 'a b'
>x is y


False

Wow. So it seems that the action of "is" on immutables is unspecified
and implementation dependent, thus useless to the programmer.


Absolutely not! "is" does what it does, and the definition of what it
does is very explicit. It checks *identity*, not equality. In both
examples above, the code is semantically meaningless because you are
checking identity on two things which you just created at the command
line, out of thin air. They may or may not be identical, but whether
they are or not has no importance.

I'm not being very clear, but what I mean is that "is" should be used
when *identity* is important to you. For example, you have a particular
object and you want to check whether a method call returns that
particular object, perhaps as a "sentinel" value. "is" is what you want
here, because you are checking whether *that specific object* is being
returned, not whether the returned item equals that object in value.

There are very good (and correct) times to use "is", but the trivial
examples above aren't them...

-Peter
Jul 18 '05 #9
>>>>> "Axel" == Axel Boldt <ax*******@yahoo.com> writes:

Axel> David MacQuigg <dm*@gain.com> wrote
>>> x = 'akdijfkdienlskfi'
>>> y = 'akdijfkdienlskfi'
>>> x is y

True
>>> x = 'a b'
>>> y = 'a b'
>>> x is y

False


Axel> Wow. So it seems that the action of "is" on immutables is
Axel> unspecified and implementation dependent, thus useless to the
Axel> programmer.

No, its behavior is quite well-specified. It does a pointer comparison.
Here is my "is" rule:

Use "is" to compare two objects only if one is explicitly known to be a
singleton defined by the language (None, Ellipsis, True, False).

and its corrolary:

Never use "is" to compare two programmer-defined variables.

Note that even though I "know" that small integers, identifier-like strings
and the null tuple are all shared objects, the language implementation is
free to change. Those are simply optimizations which you can't rely on.
Use "==" when comparing integers, strings and tuples.

Trying to use "is" when you want a performance improvement is generally
unwise. There is a performance hit going from "is" to "==", but it's
probably going be down in the noise compared to all the other things a
significant program needs to do. Ordered from fastest to slowest, timing a
pass statement, "a is b", "a == b" and a call to a function that only
executes a pass statement:

% timeit.py -s "a = b = 'frankie and johnny'" "pass"
10000000 loops, best of 3: 0.132 usec per loop
% timeit.py -s "a = b = 'frankie and johnny'" "a is b"
1000000 loops, best of 3: 0.372 usec per loop
% timeit.py -s "a = b = 'frankie and johnny'" "a == b"
1000000 loops, best of 3: 0.491 usec per loop
% timeit.py -s "def f(): pass" "f()"
1000000 loops, best of 3: 1.1 usec per loop

"a == b" is still twice as fast as a null function call.

Moral of the story: stop writing code that contains so many
functions. <wink>

Skip

Jul 18 '05 #10
At some point, ax*******@yahoo.com (Axel Boldt) wrote:
David MacQuigg <dm*@gain.com> wrote
>>> x = 'akdijfkdienlskfi'
>>> y = 'akdijfkdienlskfi'
>>> x is y True
>>> x = 'a b'
>>> y = 'a b'
>>> x is y

False


And you get different results in different contexts:
In [17]: def f():
....: x = 'a b'
....: y = 'a b'
....: return x is y
....:
In [18]: f()
Out[18]: True
Wow. So it seems that the action of "is" on immutables is unspecified
and implementation dependent, thus useless to the programmer.
No, it's entirely specified. 'is' is 'is the same object'. The
implementation-specific part is in the *creation* of the immutable
object: when you specify 'akdijfkdienlskfi' in your code twice, the
interned object is used the second time -- so you actually only have
one object. In my example above, the compiler knew 'a b' was
duplicated, so it only has one copy of 'a b' stored in the function object.
Maybe one could redefine "is" on immutables as follows: for strings
and numbers it acts as "==", for tuples it acts as componentwise "is".
That would be a more useful operator IMHO.


Why? If what you need is equality, and not object identity, use '=='.

Personally, almost all my uses of 'is' are of the form 'x is None' or
'x is not None'.

--
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
Jul 18 '05 #11
Axel Boldt wrote:
David MacQuigg <dm*@gain.com> wrote
>> x = 'akdijfkdienlskfi'
>> y = 'akdijfkdienlskfi'
>> x is y

True
>> x = 'a b'
>> y = 'a b'
>> x is y

False


Wow. So it seems that the action of "is" on immutables is unspecified
and implementation dependent, thus useless to the programmer.


It's less useful for testing mere equivalence, yes, because that's not
what it's intended to do. It tests identity. Here whether the two
strings are not just equal but _identical objects_ is an implementation
detail. If you ever rely on this behavior, your code will not be
portable to other implementations of Python.

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ Here day fights with night.
-- (the last words of Victor Hugo)
Jul 18 '05 #12
Skip Montanaro wrote:
Here is my "is" rule:

Use "is" to compare two objects only if one is explicitly known to
be a
singleton defined by the language (None, Ellipsis, True, False).


I'd add "or defined by the programmer within his code." Although
admittedly I don't use it that way much.

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ Here day fights with night.
-- (the last words of Victor Hugo)
Jul 18 '05 #13
On Tue, 16 Mar 2004 18:00:04 -0500, co**********@physics.mcmaster.ca
(David M. Cooke) wrote:
Personally, almost all my uses of 'is' are of the form 'x is None' or
'x is not None'.


Here are some more test results (averaging 10,000 evaluations in a
tight loop):

time (sec) %
Test 1: 3.68E-007 100.0 F is False
Test 2: 4.87E-007 132.1 F == False
Test 3: 3.71E-007 100.0 N is None
Test 4: 5.51E-007 148.6 N == None

The '== None' test is 49% slower than 'is None', but in absolute time,
the difference is only 180nec (on my new, but not top-speed PC). So
it would take about 10 million of these comparisons in a short time to
make a noticable difference to the user.

I can't see where the 'is' test would *ever* be needed for the above
comparisons.

-- Dave

Jul 18 '05 #14
"Axel Boldt" <ax*******@yahoo.com> wrote in message
news:40**************************@posting.google.c om...
Wow. So it seems that the action of "is" on immutables is unspecified
and implementation dependent, thus useless to the programmer.
Hardly. It has two fundamental properties, which can sometimes be useful:

1) If x and y refer to the same object, "x is y" yields True.

2) If "x is y" yields True, "x==y" also yields True. Equivalently, if
"x==y" yields False, "x is y" also yields False.
Maybe one could redefine "is" on immutables as follows: for strings
and numbers it acts as "==", for tuples it acts as componentwise "is".
That would be a more useful operator IMHO.


Can you give a realistic example of code that would benefit from such a
change?
Jul 18 '05 #15
Andrew Koenig wrote:


"Axel Boldt" <ax*******@yahoo.com> wrote in message
news:40**************************@posting.google.c om...
Wow. So it seems that the action of "is" on immutables is unspecified
and implementation dependent, thus useless to the programmer.


Hardly. It has two fundamental properties, which can sometimes be useful:

1) If x and y refer to the same object, "x is y" yields True.

2) If "x is y" yields True, "x==y" also yields True. Equivalently, if
"x==y" yields False, "x is y" also yields False.


Python 2.2.3c1 (#12, May 27 2003, 21:32:04)
[GCC 2.95.4 20011002 (Debian prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
class a: .... def __eq__(x,y): return 0
.... b = a()
b is b 1 b == b

0
So I don't think we can call it a "fundamental property" (unless the
language has changed, which actually wouldn't surprise me).
--
CARL BANKS http://www.aerojockey.com/software
"If you believe in yourself, drink your school, stay on drugs, and
don't do milk, you can get work."
-- Parody of Mr. T from a Robert Smigel Cartoon
Jul 18 '05 #16
David MacQuigg wrote:
On Tue, 16 Mar 2004 18:00:04 -0500, co**********@physics.mcmaster.ca
(David M. Cooke) wrote:
Personally, almost all my uses of 'is' are of the form 'x is None' or
'x is not None'.


Here are some more test results (averaging 10,000 evaluations in a
tight loop):

time (sec) %
Test 1: 3.68E-007 100.0 F is False
Test 2: 4.87E-007 132.1 F == False
Test 3: 3.71E-007 100.0 N is None
Test 4: 5.51E-007 148.6 N == None

The '== None' test is 49% slower than 'is None', but in absolute time,
the difference is only 180nec (on my new, but not top-speed PC). So
it would take about 10 million of these comparisons in a short time to
make a noticable difference to the user.

I can't see where the 'is' test would *ever* be needed for the above
comparisons.

Say you define the following class:

class SomeRankedObject:
def __init__(self,rank):
self.rank = rank
def __cmp__(self,other):
return cmp(self.rank,other.rank)
Now, try to test it against None with "==":

x = SomeRankedObject()
x == None
Oops, the Python interpretter just chewed you out for trying to access
the nonexistent 'rank' attribute of the None object.

If you want to test whether two expressions are the same object, use
"is". Otherwise, use "==". Period. It's as close to an absolute
rule as you'll ever find in programming.
--
CARL BANKS http://www.aerojockey.com/software
"If you believe in yourself, drink your school, stay on drugs, and
don't do milk, you can get work."
-- Parody of Mr. T from a Robert Smigel Cartoon
Jul 18 '05 #17
Skip Montanaro <sk**@pobox.com> wrote in message news:<ma***********************************@python .org>...
No, its behavior is quite well-specified. It does a pointer comparison.
Here is my "is" rule:

Use "is" to compare two objects only if one is explicitly known to be a
singleton defined by the language (None, Ellipsis, True, False).

and its corrolary:

Never use "is" to compare two programmer-defined variables.

What about when it is an object explicitly known to be singleton
defined by the programmer. ;)

Another possible use, would be to type test, eg. 'foo.__class__ is
Foo', bearing in mind that one should avoid type testing in favour of
polymorphism.
Jul 18 '05 #18
"Andrew Koenig" <ar*@acm.org> wrote
"Axel Boldt" <ax*******@yahoo.com> wrote

Maybe one could redefine "is" on immutables as follows: for strings
and numbers it acts as "==", for tuples it acts as componentwise "is".
That would be a more useful operator IMHO.


Can you give a realistic example of code that would benefit from such a
change?


Well, componentwise "is" on tupels is clearly useful, and not
available with a single operator right now. On the other hand, I don't
think there can be any realistic example where the current version of
"is" on immutables would be useful. Why would anybody ever want to
know whether two strings or tupels are internally stored at the same
location, other than to deduce details of the Python implementation?
In addition, I claim that my redefinition avoids hard to find bugs:
it's entirely possible that some people use "is" on strings, in the
mistaken belief (based on some small examples) that it is faster and
that Python always stores equal strings at the same location [I was
about to do just that, and that's why I started this whole thread].
Their programs may run correctly on some machines and not on others.
Thirdly, my redefinition would reduce the number of unspecified
implementation dependencies of the language. Note that "is" for
mutable objects is an important operator with well-defined semantics
and is not implementation dependent at all, only its behavior for
immutable objects is.

Lastly, using my redefinition of "is", we have the following nice
property for all objects a and b (mutable or immutable):

a is b iff in any code block not containing "id()" or "is", any
(or all) occurrances of a can be replaced by b, with
identical results

In the current implementation, the above equivalence only holds if we
remove "not containing id() or is", and then the statement becomes a
mere tautology without nutritious value.

Axel
Jul 18 '05 #19
On Wed, 17 Mar 2004 02:42:49 GMT, Carl Banks
<im*****@aerojockey.invalid> wrote:
David MacQuigg wrote:
On Tue, 16 Mar 2004 18:00:04 -0500, co**********@physics.mcmaster.ca
(David M. Cooke) wrote:
Personally, almost all my uses of 'is' are of the form 'x is None' or
'x is not None'.
Here are some more test results (averaging 10,000 evaluations in a
tight loop):

time (sec) %
Test 1: 3.68E-007 100.0 F is False
Test 2: 4.87E-007 132.1 F == False
Test 3: 3.71E-007 100.0 N is None
Test 4: 5.51E-007 148.6 N == None

The '== None' test is 49% slower than 'is None', but in absolute time,
the difference is only 180nec (on my new, but not top-speed PC). So
it would take about 10 million of these comparisons in a short time to
make a noticable difference to the user.

I can't see where the 'is' test would *ever* be needed for the above
comparisons.

Say you define the following class:

class SomeRankedObject:
def __init__(self,rank):
self.rank = rank
def __cmp__(self,other):
return cmp(self.rank,other.rank)
Now, try to test it against None with "==":

x = SomeRankedObject()
x == None
Oops, the Python interpretter just chewed you out for trying to access
the nonexistent 'rank' attribute of the None object.


Here is the test using Python 2.3.3:
x = SomeRankedObject() ....
TypeError: __init__() takes exactly 2 arguments (1 given) <== AS
EXPECTED x = SomeRankedObject(17)
x == None False <== AS EXPECTED

Which version of Python are you using?
If you want to test whether two expressions are the same object, use
"is". Otherwise, use "==". Period. It's as close to an absolute
rule as you'll ever find in programming.


Your missing the point. The question is why do we ever need to test
'x is None' instead of 'x == None'.

We should keep the definitions of 'is' and '==' as they are, but
discourage the use of 'is' unless you really do care if the tested
objects are the same objects in memory.

The importance of this is that implementation can change, even for
something as simple as the None object. We just had a long discussion
on enhancing the Reload() function, and concluded that the desired
change (updating all references to reloaded objects) would require
preserving a unique identity for simple objects like 'a = 2', 'b =
None', etc., in the reloaded module. So if this change is made, you
might find in some future version of Python that 'b is c' returns
False even though they have both been set to None.

Here is my "is" rule:

Use 'is' to compare two references only if it is important that
they refer to the same object in memory.

and its corrolary:

Use '==' if all you are concerned about is equality of value.

-- Dave

Jul 18 '05 #20

"Axel Boldt" <ax*******@yahoo.com> wrote in message
news:40**************************@posting.google.c om...
"is" on immutables would be useful. Why would anybody ever want to
know whether two strings or tupels are internally stored at the same
location, other than to deduce details of the Python implementation?


Deducing details of the implementation *is*, for people with a certain
curiosity, a legitimate usage, in spite of your distain for such.
Explaining the bahavior of

a=[1]
b=a
a[0]=2
print b

is another use for 'is'.

Terry J. Reedy


Jul 18 '05 #21
"Terry Reedy" <tj*****@udel.edu> wrote in message
news:ma***********************************@python. org...
Deducing details of the implementation *is*, for people with a certain
curiosity, a legitimate usage, in spite of your distain for such.
Explaining the bahavior of

a=[1]
b=a
a[0]=2
print b

is another use for 'is'.


Lists are mutable, so there's no proposal to change the behavior of "is" in
this context.
Jul 18 '05 #22
"Axel Boldt" <ax*******@yahoo.com> wrote in message
news:40**************************@posting.google.c om...
Lastly, using my redefinition of "is", we have the following nice
property for all objects a and b (mutable or immutable):

a is b iff in any code block not containing "id()" or "is", any
(or all) occurrances of a can be replaced by b, with
identical results


Interesting idea. Perhaps you should consider writing a PEP.
Jul 18 '05 #23
"Terry Reedy" <tj*****@udel.edu> wrote
"Axel Boldt" <ax*******@yahoo.com> wrote
"is" on immutables would be useful. Why would anybody ever want to
know whether two strings or tupels are internally stored at the same
location, other than to deduce details of the Python implementation?


Deducing details of the implementation *is*, for people with a certain
curiosity, a legitimate usage, in spite of your distain for such.


No disdain whatsoever, I do it all the time myself. However, even
after my proposed redefinition of "is" for immutables, the function
id() would remain available for the curious.
Explaining the bahavior of

a=[1]
b=a
a[0]=2
print b

is another use for 'is'.


Certainly, and there are many other real world use cases for "is",
just not for "is" on immutables.

Axel
Jul 18 '05 #24
ax*******@yahoo.com (Axel Boldt) wrote in message news:<40**************************@posting.google. com>...
Why would anybody ever want to
know whether two strings or tupels are internally stored at the same
location, other than to deduce details of the Python implementation?


Most obviously to tell whether they are the same object or not.
While this is not an issue with simple strings, have you considered
what effect your suggestions would have on classes inheriting from
str?

For instance I might have a class 'Name', in a names database, which
is a specialised string. In this case '==' function looks to the
contents of the strings being compared, while 'is' tells me whether
these two strings are the same object. Thus "if name0 == name1 and
not name0 is name1" will tell me that I am dealing with a duplicate
record. Now this might not be the best way to find duplicates in
practice, it's simply first thing that popped into my head in response
to your question. But I don't think I'm able to anticipate all the
ways in which all programmers might want to apply the distinction
between equivalence and identity in their programs? Are you?

By the way you /have/ written a program in which a large (or at least
important) part of the logic was contained in the __eq__ method to the
class you created, haven't you? I mean you wouldn't really be in a
situation to advocate a redefinition of the identity/equivalence
relationship unless you had, would you?
Jul 18 '05 #25
Axel Boldt wrote:
Lastly, using my redefinition of "is", we have the following nice
property for all objects a and b (mutable or immutable):

a is b iff in any code block not containing "id()" or "is", any
(or all) occurrances of a can be replaced by b, with
identical results

In the current implementation, the above equivalence only holds if we
remove "not containing id() or is", and then the statement becomes a
mere tautology without nutritious value.


I'm at a loss to understand why you want to change the behavior of the
`is' operator if you aren't clear on what it's used for in the first
place.

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ Does the true light / Of love come in flashes
-- Sandra St. Victor
Jul 18 '05 #26
At some point, David MacQuigg <dm*@gain.com> wrote:
On Tue, 16 Mar 2004 18:00:04 -0500, co**********@physics.mcmaster.ca
(David M. Cooke) wrote:
Personally, almost all my uses of 'is' are of the form 'x is None' or
'x is not None'.


Here are some more test results (averaging 10,000 evaluations in a
tight loop):

time (sec) %
Test 1: 3.68E-007 100.0 F is False
Test 2: 4.87E-007 132.1 F == False
Test 3: 3.71E-007 100.0 N is None
Test 4: 5.51E-007 148.6 N == None

The '== None' test is 49% slower than 'is None', but in absolute time,
the difference is only 180nec (on my new, but not top-speed PC). So
it would take about 10 million of these comparisons in a short time to
make a noticable difference to the user.

I can't see where the 'is' test would *ever* be needed for the above
comparisons.


I do a lot of stuff with arrays in Numeric, which override __eq__ to
elementwise comparision:

Python 2.3.3 (#2, Feb 24 2004, 09:29:20)
[GCC 3.3.3 (Debian)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
import Numeric
x = Numeric.array([0,1,2,3])
x == None array([0,0,0,0]) bool(x == None) False x is None False x == False array([1,0,0,0]) bool(x == False) True x is False False bool(x == True) True bool(x == True and x == False)

True

[Ok, so bool(x == None) returns False, which is good, but imagine the
overhead if x was an array of several million elements. x == None
would allocate a new array of the same size.]

--
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
Jul 18 '05 #27
af*****@yahoo.co.uk (Asun Friere) wrote
ax*******@yahoo.com (Axel Boldt) wrote
Why would anybody ever want to
know whether two strings or tupels are internally stored at the same
location, other than to deduce details of the Python implementation?


Most obviously to tell whether they are the same object or not.
While this is not an issue with simple strings, have you considered
what effect your suggestions would have on classes inheriting from
str?


Indeed I have not. Probably because basic built-in strings form a type
that's not a class and you can't inherit from it.
For instance I might have a class 'Name', in a names database, which
is a specialised string. In this case '==' function looks to the
contents of the strings being compared, while 'is' tells me whether
these two strings are the same object. Thus "if name0 == name1 and
not name0 is name1" will tell me that I am dealing with a duplicate
record.
If you make Name a class that contains a string as a data attribute,
then "is" on Name objects will work as always, since Names aren't
immutable. To test whether you have duplicates, you can use "is" on
Names.

Now, rather than test "is" on Name objects, one could be tempted to
test "is" on the string attributes instead. Note that sometimes
strings created by completely different parts of a program compare as
"is-identical". Sometimes they don't, even though they are "==-equal".
It's implementation dependent. Name is broken. My proposal would
eliminate this very programming mistake.
By the way you /have/ written a program in which a large (or at least
important) part of the logic was contained in the __eq__ method to the
class you created, haven't you?
No.
I mean you wouldn't really be in a
situation to advocate a redefinition of the identity/equivalence
relationship unless you had, would you?


Why not?

Axel
Jul 18 '05 #28
> Indeed I have not. Probably because basic built-in strings form a type
that's not a class and you can't inherit from it.

Mostly because I am interested in the counter argument:

class mynewstr(str):
.... pass
....
s = mynewstr()
dir(s)

<<list of str stuff>>
Jul 18 '05 #29

At some point, David MacQuigg <dm*@gain.com> wrote:
I can't see where the 'is' test would *ever* be needed for the above
comparisons.

On Thu, 18 Mar 2004 01:17:53 -0500, co**********@physics.mcmaster.ca
(David M. Cooke) wrote:I do a lot of stuff with arrays in Numeric, which override __eq__ to
elementwise comparision:

Python 2.3.3 (#2, Feb 24 2004, 09:29:20)
[GCC 3.3.3 (Debian)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
import Numeric
x = Numeric.array([0,1,2,3])
x == Nonearray([0,0,0,0]) bool(x == None)False x is NoneFalse x == Falsearray([1,0,0,0]) bool(x == False)True x is FalseFalse bool(x == True)True bool(x == True and x == False)True

[Ok, so bool(x == None) returns False, which is good, but imagine the
overhead if x was an array of several million elements. x == None
would allocate a new array of the same size.]


For the rare case where storage of None elements is an issue, could
you define your own 'none' object, and simply point all references to
it. That would allow you to use 'is', avoiding the overhead of '==',
and not mess with the normal definition of '=='. Most importantly, it
would allow you to use 'is' with confidence that a Python
implementation change, or a move to a new platform, won't trash your
program.
class none: def __repr__(self):
return 'none'
... whatever other attributes you need for 'none'
n0 = none()
n1 = n2 = n0
n1 == n2 True n1 is n2 True n1 none


-- Dave

Jul 18 '05 #30

On 18-mrt-04, at 14:14, Axel Boldt wrote:
af*****@yahoo.co.uk (Asun Friere) wrote
ax*******@yahoo.com (Axel Boldt) wrote

Why would anybody ever want to
know whether two strings or tupels are internally stored at the same
location, other than to deduce details of the Python implementation?


Most obviously to tell whether they are the same object or not.
While this is not an issue with simple strings, have you considered
what effect your suggestions would have on classes inheriting from
str?


Indeed I have not. Probably because basic built-in strings form a type
that's not a class and you can't inherit from it.


Yes you can:

Python 2.3 (#1, Sep 13 2003, 00:49:11)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
class MyStr(str): pass .... x = MyStr("hello")
type(x) <class '__main__.MyStr'>

Jul 18 '05 #31
For what it's worth: the idea of changing the meaning of 'is' been
discussed on the PyDev (development) list for a couple of days. GvR posted
this a few hours ago ('the code' refers to an example misusing 'is'):

"I'm ready to pronounce. The code is buggy. There are good reasons to
keep 'is' the way it always was. The definition of 'is' ain't gonna
change. So be it"

Terry J. Reedy


Jul 18 '05 #32
"DomF" <fidtz@clara#spam#.co.uk> wrote in message news:<10****************@lotis.uk.clara.net>...
Indeed I have not. Probably because basic built-in strings form a type
that's not a class and you can't inherit from it.

Mostly because I am interested in the counter argument:

class mynewstr(str):
... pass
...
s = mynewstr()
dir(s)

<<list of str stuff>>


I stand corrected, I don't think there is a counter argument. So then
the objection of Asun Friere remains: could a redefinition of "is" for
strings affect the behavior of classes derived from str? I don't know.

Axel
Jul 18 '05 #33
ax*******@yahoo.com (Axel Boldt) wrote in message news:<40**************************@posting.google. com>...
Probably because basic built-in strings form a type
that's not a class and you can't inherit from it.
You sure can! (Providing, of course your python is >= 2.2) Try this:

class MyString (str) :
pass
foo = MyString('the things you can do in python!')
foo.__class__ is MyString
isinstance(foo, str)
MyString.mro()
For instance I might have a class 'Name', in a names database, which
is a specialised string. In this case '==' function looks to the
contents of the strings being compared, while 'is' tells me whether
these two strings are the same object. Thus "if name0 == name1 and
not name0 is name1" will tell me that I am dealing with a duplicate
record.


If you make Name a class that contains a string as a data attribute ...


Now you know the above all this is irrelevant, yes? I mean
composition may be a valid strategy, but it doesn't really address the
question, of how your proposed changes would affect inheritence.

The problem with my example (well it's probably a problem with the
Python definition :P), is that while you could be pretty sure that the
condition "if name0 == name1 and not name0 is name1" indicates a
duplicate, its facility to find /all/ duplicates is implementation
dependent (ie it works because only built-in types like 'int' and
'str' are 'cached' to the same objects, and programmer defined classes
such as 'Name' or 'MyString' are not). Which leads to my next point
....
a program in which a large (or at least
important) part of the logic was contained in the __eq__ method to the
class you created


It might be instructive to play with the difference between identity
and equivalence in the abstract. What I mean is this, imagine that
'is' really means 'is' rather the 'is located at.' Given the current
implementation (and probably any future implementation), one can do
this, bearing in mind the caveat that special considerations apply
with regard to some built-in types.

Doing so might lead to an appreciation the power of this distinction
in an abstract OO context, which in turn might lead towards advocating
a very different kind of change to the meaning of 'is.' Rather than
inconsistently conflating the concept of identity with equivalence
(which imo your proposal does), one might argue for a guarantee that
an implementation /never/ cache different instances of a programmer
created class to the same memory location.
I mean you wouldn't really be in a
situation to advocate a redefinition of the identity/equivalence
relationship unless you had, would you?


Why not?


Because you would be advocating a change to an aspect of the language
you don't use, but which other programmers do.
Jul 18 '05 #34

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3659
by: jerrygarciuh | last post by:
Hi all, I am iterating through a result set to generate a second set of queries but no matter what I do I get the error Warning: mysql_num_rows(): supplied argument is not a valid MySQL result...
2
1928
by: maceo | last post by:
I have a script that will print out the results of a table and make a calculation of a total of one of the columns. See example: <?php /* Database connection */...
4
14530
by: John Davis | last post by:
<html> <body> <Form action="calc.asp" method="post" name="calc"> <P>NUM1: <input type="text" name="num1"> <P>NUM2: <input type="text" name="num2"> <P>RESULT: <input type="text" name="result">...
2
2328
by: swhite76 | last post by:
I have a section of code that adds some double values and gives an incorrect result. This occurs with data that isn't really waht I would call high precision. An example is the following code...
4
1906
by: Tao Wang | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, I am quite confused on a equation, as following: #include <iostream> int main(){ int i = 2;
3
3820
by: Michael C# | last post by:
Hi all, I'm sending a command via SqlClient, and it returns two result sets. I can successfully read the first result set, but how can I access the second result set? Here's an example of my...
12
2172
by: Mick_fae_Glesga | last post by:
OK, the solution to this is probably blindingly obvious to everyone, but... surely it can't be right. I am compiling with borland bcc32 free compiler this piece of code is designed to identify...
9
7401
by: Petr Vileta | last post by:
Hi, I'm new here and excuse me if this question was be here earlier. I have a simple code <html><body> <?php <?php $link = mysql_connect("localhost", "user", "password") or die("Grr: " ....
9
2535
by: JRough | last post by:
I tried to pass the $result from a mysql_query in a url like this line Header("Location:clm_historyXL.php?_result=".$result); but on the redirect location clm_history.php page I get an error on...
3
2161
by: JRough | last post by:
I want to save two variables in a $_SESSION for use in another page: $_SESSION = $mark; $_SESSION = $num; then on the other page I did this to get the value: $mark =$_SESSION; $num =...
0
7039
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
6904
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7080
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6735
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5326
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4476
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
2992
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
2977
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
558
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.