Re: This code not working, need suggetions

2012-04-23 Thread Chris Rebert
On Sun, Apr 22, 2012 at 11:16 PM, Anirudh Srinivasan 
wrote:
>
> My code lists the files and directory under a folder and if we want to
> read the file it uses the function  cat.
>
> But the function cat(get_file) is not working , any suggetions?

Please specifically state exactly how it's deviating from the desired
behavior (including the full text of any error messages and/or
exception tracebacks, though I don't think those will apply here).
I note that you don't actually call cat() anywhere in your program.

> Here is my code:
>
>
> #!/usr/bin/python
>
> import os
> import sys
> import commands
> #import cat

Such an import (if uncommented) would require you had a *module* named `cat`.

> def listdir(s):

I would suggest renaming this function to avoid confusion with os.listdir().

>try:
>   file  = os.listdir(s)

Don't use `file` as a variable name. It shadows the name of the
built-in `file` type.
Also, `file` isn't a sensible variable name in this context; it's a
list (as opposed to a single item) and may also contain directory
names. And it contains strings rather than file objects.

>   for files in file:
>   path = os.path.join(s, files)
>   print path
>   #cmd = 'ls -l '+ path
>   #g= commands.getstatusoutput(cmd)

The `commands` module has been deprecated. Its successor is `subprocess`:
http://docs.python.org/library/subprocess.html

>   #print g[1]
>except OSError:
>   print "No such file or directory"
>
>
> def main():
>   listdir(sys.argv[1])
>
>
> if __name__ == "__main__":
>   main()

`if __name__ == "__main__":` should normally come at the end of the
script, after all `def`s.

>
> def cat(get_file):
>   f = open(get_file, "rU")
>   text = f.read()
>   print text,

You should `.close()` the file once you're done with it. Or use the
`with` statement (http://www.python.org/dev/peps/pep-0343/ ).

> get_file = raw_input("Which file would you like to browse ?")

Presumably this line should be under your `if __name__ ==
"__main__":`? And you're not actually doing anything with `get_file`
after you obtain it from the user...

Regards,
Chris
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: This code not working, need suggetions

2012-04-23 Thread Min Yu
try this code out. The lsdir function and cat function are both used in
main().

The bash commands are as following:

yumin@yumin-think:~/src/test/python/community$ python list.py `pwd`
/home/yumin/src/test/python/community
list.py
file1
file2
Which file would you like to browse ?file1
This is file1
Which file would you like to browse ?file2
This is file2
Which file would you like to browse ?
yumin@yumin-think:~/src/test/python/community$
--
#!/usr/bin/python


import os
import sys
import commands
#import cat

def listdir(s):
try:
print s
files  = os.listdir(s)
for f in files:
#path = os.path.join(s, f)
#print path
print f
except OSError:
print "No such file or directory"

def cat(get_file):
f = open(get_file, "rU")
text = f.read()
print text,

def main():
working_dir = sys.argv[1]
listdir(working_dir)
On = True
while On:
get_file = raw_input("Which file would you like to browse ?")
if get_file == '':
On = False
#break
else:
cat(os.path.join(working_dir,get_file))

if __name__ == "__main__":
main()



2012/4/23 Chris Rebert 

> On Sun, Apr 22, 2012 at 11:16 PM, Anirudh Srinivasan 
> wrote:
> >
> > My code lists the files and directory under a folder and if we want to
> > read the file it uses the function  cat.
> >
> > But the function cat(get_file) is not working , any suggetions?
>
> Please specifically state exactly how it's deviating from the desired
> behavior (including the full text of any error messages and/or
> exception tracebacks, though I don't think those will apply here).
> I note that you don't actually call cat() anywhere in your program.
>
> > Here is my code:
> >
> >
> > #!/usr/bin/python
> >
> > import os
> > import sys
> > import commands
> > #import cat
>
> Such an import (if uncommented) would require you had a *module* named
> `cat`.
>
> > def listdir(s):
>
> I would suggest renaming this function to avoid confusion with
> os.listdir().
>
> >try:
> >   file  = os.listdir(s)
>
> Don't use `file` as a variable name. It shadows the name of the
> built-in `file` type.
> Also, `file` isn't a sensible variable name in this context; it's a
> list (as opposed to a single item) and may also contain directory
> names. And it contains strings rather than file objects.
>
> >   for files in file:
> >   path = os.path.join(s, files)
> >   print path
> >   #cmd = 'ls -l '+ path
> >   #g= commands.getstatusoutput(cmd)
>
> The `commands` module has been deprecated. Its successor is `subprocess`:
> http://docs.python.org/library/subprocess.html
>
> >   #print g[1]
> >except OSError:
> >   print "No such file or directory"
> >
> >
> > def main():
> >   listdir(sys.argv[1])
> >
> >
> > if __name__ == "__main__":
> >   main()
>
> `if __name__ == "__main__":` should normally come at the end of the
> script, after all `def`s.
>
> >
> > def cat(get_file):
> >   f = open(get_file, "rU")
> >   text = f.read()
> >   print text,
>
> You should `.close()` the file once you're done with it. Or use the
> `with` statement (http://www.python.org/dev/peps/pep-0343/ ).
>
> > get_file = raw_input("Which file would you like to browse ?")
>
> Presumably this line should be under your `if __name__ ==
> "__main__":`? And you're not actually doing anything with `get_file`
> after you obtain it from the user...
>
> Regards,
> Chris
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie, homework help, please.

2012-04-23 Thread Jean-Michel Pichavant

someone wrote:
 I have a professor who should be [*snip*] the best person I've ever met 


I hope he's (not) reading this list :o)

Non python advise : be very careful on the internet.

JM


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


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Alexander Blinne
Am 21.04.2012 14:51, schrieb gst:
> Hi,
> 
> I played (python3.2) a bit on that and :
> 
> case 1) Ok to me (right hand side is a tuple, whose elements are evaluated 
> one per one and have same effect as your explanation (first [] is destroyed 
> right before the second one is created) :
> 
 x, y = id([]), id([])
 x == y
> True

> 
> 
> case 2) also ok to me:
> 
 x = id([]) ; y = id([])
 x == y
> True

> 
> 
> case 3) NOT ok to me :
> 
 x = id([])
 y = id([])
 x == y
> False

> 
> 
> case 4) ok to me :
> 
 def f():
>   x = id([])
>   y = id([])
>   return x == y
> 
 f()
> True

> 
> 
> I'd have thought that cases 2&3 are totally, while 3&4 nearly, syntactically 
> equal and that case 3 is the incorrect result..
> 
> how would you explain case 3 vs cases 2 and 4 ??

It is simply not defined if, after creation and destruction of an empty
list with some id, a newly created empty list should carry the same id
or not. In cases 1,2 and 4 it happens, but in case 3 it doesn't. This is
simply an implementation detail and neither behaviour is right or wrong.

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


PyOpenCV -- help?

2012-04-23 Thread Virgil Stokes
I have tried to install PyOpenCV without success (error occurs during the 
installation procedure).  I reported the problem to the opencv user group 
(http://groups.google.com/group/ctypes-opencv) but this group has not been 
active since June of last year.


Anyone know of how to get help with PyOpenCV?


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


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread John Nagle

On 4/22/2012 9:34 PM, Steven D'Aprano wrote:

On Sun, 22 Apr 2012 12:43:36 -0700, John Nagle wrote:


On 4/20/2012 9:34 PM, john.tant...@gmail.com wrote:

On Friday, April 20, 2012 12:34:46 PM UTC-7, Rotwang wrote:


I believe it says somewhere in the Python docs that it's undefined and
implementation-dependent whether two identical expressions have the
same identity when the result of each is immutable


 Bad design.  Where "is" is ill-defined, it should raise ValueError.


"is" is never ill-defined. "is" always, without exception, returns True
if the two operands are the same object, and False if they are not. This
is literally the simplest operator in Python.

John, you've been using Python for long enough that you should know this.
I can only guess that you are trolling, although I can't imagine why.


   Because the language definition should not be what CPython does.
As PyPy advances, we need to move beyond that.

John Nagle
--
http://mail.python.org/mailman/listinfo/python-list


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Kiuhnm

On 4/22/2012 21:43, John Nagle wrote:

On 4/20/2012 9:34 PM, john.tant...@gmail.com wrote:

On Friday, April 20, 2012 12:34:46 PM UTC-7, Rotwang wrote:


I believe it says somewhere in the Python docs that it's undefined and
implementation-dependent whether two identical expressions have the same
identity when the result of each is immutable


Bad design. Where "is" is ill-defined, it should raise ValueError.

A worse example, one which is very implementation-dependent:

http://stackoverflow.com/questions/306313/python-is-operator-behaves-unexpectedly-with-integers


 >>> a = 256
 >>> b = 256
 >>> a is b
True # this is an expected result
 >>> a = 257
 >>> b = 257
 >>> a is b
False

Operator "is" should be be an error between immutables
unless one is a built-in constant.

[...]

I can't think of a single case where 'is' is ill-defined.
You're blaming 'is' for revealing what's really going on. 'is' is /not/ 
implementation-dependent. It's /what's going on/ that's 
implementation-dependent.
"a is b" is true iff 'a' and 'b' are the same object. Why should 'is' 
lie to the user?
It does exactly what it says it does: it tells the user whether two 
objects are the same.
In C++, for greater efficiency, two objects are compared for equality by 
first checking their addresses and then their contents. 'is' would be 
perfect for that.


What I don't like is 'isinstance'. I'd prefer an infix operator 'isa' or 
'is_a'.


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


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Paul Rubin
Kiuhnm  writes:
> I can't think of a single case where 'is' is ill-defined.

If I can't predict the output of 

print (20+30 is 30+20)  # check whether addition is commutative
print (20*30 is 30*20)  # check whether multiplication is commutative

by just reading the language definition and the code, I'd have to say
"is" is ill-defined.

> You're blaming 'is' for revealing what's really going on. 'is' is
> /not/ implementation-dependent. It's /what's going on/ that's
> implementation-dependent.
> "a is b" is true iff 'a' and 'b' are the same object. Why should 'is'
> lie to the user?

Whether a and b are the same object is implementation-dependent.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Benjamin Kaplan
On Mon, Apr 23, 2012 at 1:01 PM, Paul Rubin  wrote:
>
> Kiuhnm  writes:
> > I can't think of a single case where 'is' is ill-defined.
>
> If I can't predict the output of
>
>    print (20+30 is 30+20)  # check whether addition is commutative
>    print (20*30 is 30*20)  # check whether multiplication is commutative
>
> by just reading the language definition and the code, I'd have to say
> "is" is ill-defined.
>

The "is" operator is perfectly defined. But it doesn't check to see
whether two objects hold equivalent values, it checks whether they are
the same thing. You're not interested in whether 20+30 and 30+20 are
the same object, you're interested in whether they return equivalent
values which should be checked with ==.

> > You're blaming 'is' for revealing what's really going on. 'is' is
> > /not/ implementation-dependent. It's /what's going on/ that's
> > implementation-dependent.
> > "a is b" is true iff 'a' and 'b' are the same object. Why should 'is'
> > lie to the user?
>
> Whether a and b are the same object is implementation-dependent.
> --

And if I try running "from java.util import ArrayList" in CPython it
will give me an import error. It doesn't mean that the import
mechanism is broken because it returns different results in different
implementations of Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Kiuhnm

On 4/23/2012 19:01, Paul Rubin wrote:

Kiuhnm  writes:

I can't think of a single case where 'is' is ill-defined.


If I can't predict the output of

 print (20+30 is 30+20)  # check whether addition is commutative
 print (20*30 is 30*20)  # check whether multiplication is commutative

by just reading the language definition and the code, I'd have to say
"is" is ill-defined.


Counterexample:

import datetime
print(datetime.datetime.now())



You're blaming 'is' for revealing what's really going on. 'is' is
/not/ implementation-dependent. It's /what's going on/ that's
implementation-dependent.
"a is b" is true iff 'a' and 'b' are the same object. Why should 'is'
lie to the user?


Whether a and b are the same object is implementation-dependent.


My point exactly.

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


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Ian Kelly
On Mon, Apr 23, 2012 at 11:01 AM, Paul Rubin  wrote:
> Kiuhnm  writes:
>> I can't think of a single case where 'is' is ill-defined.
>
> If I can't predict the output of
>
>    print (20+30 is 30+20)  # check whether addition is commutative
>    print (20*30 is 30*20)  # check whether multiplication is commutative
>
> by just reading the language definition and the code, I'd have to say
> "is" is ill-defined.

It seems to me that one could equally argue that "+" is ill-defined,
because the output of "x + y" could just as easily be 1729 or 42.  In
either case the problem is not in the operator, but in determining
exactly what the left and right sides evaluate to.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Devin Jeanpierre
On Mon, Apr 23, 2012 at 1:21 PM, Benjamin Kaplan
 wrote:
> On Mon, Apr 23, 2012 at 1:01 PM, Paul Rubin  wrote:
> The "is" operator is perfectly defined. But it doesn't check to see
> whether two objects hold equivalent values, it checks whether they are
> the same thing. You're not interested in whether 20+30 and 30+20 are
> the same object, you're interested in whether they return equivalent
> values which should be checked with ==.

The only way to check if two values are the same or not is to compare
via is or compare the return values of id(). So you can say that is or
id() are ill-defined, or you can say that the identity of new numbers
is ill-defined, and it doesn't really make a difference, ever, because
is and id() are the only way in which object identity even _exists_ in
Python.

>> Whether a and b are the same object is implementation-dependent.
>> --
>
> And if I try running "from java.util import ArrayList" in CPython it
> will give me an import error. It doesn't mean that the import
> mechanism is broken because it returns different results in different
> implementations of Python.

Nobody is calling Python broken. "ill defined" != "broken".

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


I couldn't use the sign funcion inside of another function

2012-04-23 Thread Julio Sergio
I want to use the sign function. When I use it in in-line mode works pretty 
well:

   : sign(-20)
   : -1

However, I wrote the following code in a file, say, pp.py

def tst(x):
s = sign(x)
return(s)

Then I tried to import into my session:

  : from pp import *

When I try to use tst, this is what I get:

  
  Traceback (most recent call last):
File "", line 1, in 
File "pp.py", line 9, in tst
  s = sign(x)
  NameError: global name 'sign' is not defined


Do you have any idea why is this happening?


Thanks,

 -- Sergio.


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


Re: I couldn't use the sign funcion inside of another function

2012-04-23 Thread Chris Rebert
On Mon, Apr 23, 2012 at 11:29 AM, Julio Sergio  wrote:
> I want to use the sign function. When I use it in in-line mode works pretty
> well:
>
>   : sign(-20)
>   : -1
>
> However, I wrote the following code in a file, say, pp.py
>
> def tst(x):
>    s = sign(x)
>    return(s)
>
> Then I tried to import into my session:
>
>  : from pp import *
>
> When I try to use tst, this is what I get:
>
>  
>  Traceback (most recent call last):
>    File "", line 1, in 
>    File "pp.py", line 9, in tst
>      s = sign(x)
>  NameError: global name 'sign' is not defined
>
>
> Do you have any idea why is this happening?

There is no built-in sign() function in Python. It must be coming from
some library that you imported. You need to add that import to pp.py
so that Python knows that your module depends on that library.

Cheers,
Chris
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Robert Kern

On 4/23/12 5:04 PM, John Nagle wrote:

On 4/22/2012 9:34 PM, Steven D'Aprano wrote:

On Sun, 22 Apr 2012 12:43:36 -0700, John Nagle wrote:


On 4/20/2012 9:34 PM, john.tant...@gmail.com wrote:

On Friday, April 20, 2012 12:34:46 PM UTC-7, Rotwang wrote:


I believe it says somewhere in the Python docs that it's undefined and
implementation-dependent whether two identical expressions have the
same identity when the result of each is immutable


Bad design. Where "is" is ill-defined, it should raise ValueError.


"is" is never ill-defined. "is" always, without exception, returns True
if the two operands are the same object, and False if they are not. This
is literally the simplest operator in Python.

John, you've been using Python for long enough that you should know this.
I can only guess that you are trolling, although I can't imagine why.


Because the language definition should not be what CPython does.


It isn't. That's the point of leaving some things like the interning of certain 
special objects undefined, to make room for other implementations. You seem to 
be objecting to that for some bizarre reason.


--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Steven D'Aprano
On Mon, 23 Apr 2012 10:01:24 -0700, Paul Rubin wrote:

> Kiuhnm  writes:
>> I can't think of a single case where 'is' is ill-defined.
> 
> If I can't predict the output of
> 
> print (20+30 is 30+20)  # check whether addition is commutative
> print (20*30 is 30*20)  # check whether multiplication is
> commutative
> 
> by just reading the language definition and the code, I'd have to say
> "is" is ill-defined.

The failure to predict the result of the above has nothing to do with 
"is". Your test doesn't test what you think it does, because the output 
doesn't just depend on the behaviour of "is". Aside from the properties 
of arithmetic, the result printed depends on at least six factors:

* the behaviour of "is" (known)
* the behaviour of the Python interpreter when evaluating arithmetic
  expressions (undefined)
* the behaviour of the interpreter when creating objects (undefined)
* the presence or absence of a keyhole optimizer (undefined)
* and how aggressive it is (undefined)
* any other optimizations the compiler might apply (undefined)

The *one* factor which actually is well-defined by the language and 
completely predictable is the thing that you are John are blaming for 
your failure to predict the outcome! That's simply surreal.

It isn't the "is" operator that is ill-defined. What actually is ill-
defined is the circumstances where a Python implementation uses the same 
object for equal results. And that is as it should be. The decision to 
recreate or reuse objects when needed should not be part of the language 
definition. Why do you care whether a, b = 1+2, 5-2 creates two objects 
or one? At most, that's a quality of implementation issue. It certainly 
doesn't affect the semantics of the language.


>> You're blaming 'is' for revealing what's really going on. 'is' is /not/
>> implementation-dependent. It's /what's going on/ that's
>> implementation-dependent.
>> "a is b" is true iff 'a' and 'b' are the same object. Why should 'is'
>> lie to the user?
> 
> Whether a and b are the same object is implementation-dependent.

And that has absolutely nothing to do with the behaviour of "is". The 
"is" operator is not responsible for whether a and b are the same object.

The "is" operator has an exact definition. There is nothing ill-defined 
about the "is" operator. That definition is simple enough for me to quote 
it in full:

The operators is and is not test for object identity: x is y is
true if and only if x and y are the same object. x is not y 
yields the inverse truth value.

Taken from the last paragraph of here:
http://docs.python.org/py3k/reference/expressions.html#is


Short of having "is" be a null-op that always returns False, there are no 
changes you can make to the definition of "is" that will make "a is b" 
any more predictable.


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


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Terry Reedy

On 4/23/2012 12:38 AM, Devin Jeanpierre wrote:

On Sun, Apr 22, 2012 at 9:22 PM, Terry Reedy  wrote:

On 4/22/2012 3:43 PM, John Nagle wrote:


On 4/20/2012 9:34 PM, john.tant...@gmail.com wrote:


On Friday, April 20, 2012 12:34:46 PM UTC-7, Rotwang wrote:


I believe it says somewhere in the Python docs that it's undefined and
implementation-dependent whether two identical expressions have the same
identity when the result of each is immutable



Bad design. Where "is" is ill-defined, it should raise ValueError.



There is no ambiguity about the meaning of 'is' in Python. It is always
well-defined. So the suggestion is a nullity. The equivalent function form
in Python is


Bollocks it's well defined. We've already agreed that "1 is 1" may or
may not return True.


'We' have not so agreed. The function should tell the truth. Let me 
repeat: 'is' is a function whose two inputs are not eternal mathematical 
values but rather are computational implementation objects with finite 
lifetimes.


It is wrong to interpret the Python expression '1 is 1' as a 
mathematical expression. It simply is not such. Trying to do so only 
leads to confusion, as this thread show.


The 'is' function answers a question about the current state of a 
particular temporal computational process. Its output is well-determined 
given its actual input. Like other introspection functions, it is useful 
for testing an implementation.



Then let's just go to the definition:
http://mathworld.wolfram.com/Well-Defined.html

"An expression is called "well-defined" (or unambiguous) if its
definition assigns it a unique interpretation or value.


The definition of 'is' does just that.


The same complaint applies to your suggestion that id() is
well-defined, and I stopped reading there.


In much or most of mathematics, there is little or no concept of 
'identify' separate from 'value'. In Python, for Python objects, there 
is. This is necessary if Python is to model real life as well as do 
mathematical computations. If you do not like it, ignore it.


Since the existence of objects is time-dependent, the mapping from 
objects to ids also is. As any one time, the mapping is not only 
well-defined but bijective, so there is an inverse mapping from ids to 
objects.



--
Terry Jan Reedy

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


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Terry Reedy

On 4/23/2012 1:55 PM, Devin Jeanpierre wrote:

On Mon, Apr 23, 2012 at 1:21 PM, Benjamin Kaplan
  wrote:

On Mon, Apr 23, 2012 at 1:01 PM, Paul Rubin  wrote:
The "is" operator is perfectly defined. But it doesn't check to see
whether two objects hold equivalent values, it checks whether they are
the same thing. You're not interested in whether 20+30 and 30+20 are
the same object, you're interested in whether they return equivalent
values which should be checked with ==.


The only way to check if two values are the same or not is to compare
via is or compare the return values of id().


To quote you, 'bollocks'. The right way to compare values is with value 
comparison operators.


> So you can say that is or

id() are ill-defined, or you can say that the identity of new numbers
is ill-defined,


'numbers' do not have identity, at least not separate from value.
Concrete computational process objects do.

--
Terry Jan Reedy

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


Re: I couldn't use the sign funcion inside of another function

2012-04-23 Thread Emile van Sebille

On 4/23/2012 11:39 AM Chris Rebert said...

On Mon, Apr 23, 2012 at 11:29 AM, Julio Sergio  wrote:

I want to use the sign function. When I use it in in-line mode works pretty
well:

   : sign(-20)
   : -1

However, I wrote the following code in a file, say, pp.py

def tst(x):
s = sign(x)
return(s)

Then I tried to import into my session:

  : from pp import *

When I try to use tst, this is what I get:

  
  Traceback (most recent call last):
File "", line 1, in
File "pp.py", line 9, in tst
  s = sign(x)
  NameError: global name 'sign' is not defined


Do you have any idea why is this happening?


There is no built-in sign() function in Python. It must be coming from
some library that you imported. You need to add that import to pp.py
so that Python knows that your module depends on that library.


There is math.copysign you could use:

>>> import math

>>> help(math.copysign)
Help on built-in function copysign in modul

copysign(...)
copysign(x, y)

Return x with the sign of y.

>>> math.copysign(1,-1)
-1.0
>>> math.copysign(1,1)
1.0

>>>
>>> def sign(y):
... return int(math.copysign(1,y))
...
>>> sign(1)
1
>>> sign(0)
1
>>> sign(-1)
-1

Emile

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


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Devin Jeanpierre
On Mon, Apr 23, 2012 at 3:58 PM, Steven D'Aprano
 wrote:
>> Whether a and b are the same object is implementation-dependent.
>
> And that has absolutely nothing to do with the behaviour of "is". The
> "is" operator is not responsible for whether a and b are the same object.

Heh, it has everything to do with the behavior of is. Although I know
what you mean.

> Short of having "is" be a null-op that always returns False, there are no
> changes you can make to the definition of "is" that will make "a is b"
> any more predictable.

Well, no. Immutable objects could always compare equal, for example.
This is more expensive though. is as-it-stands is very quick to
execute, which is probably attractive to some people (especially for
its used in detecting special constants).

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


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Devin Jeanpierre
On Mon, Apr 23, 2012 at 3:59 PM, Terry Reedy  wrote:
>>
>> Bollocks it's well defined. We've already agreed that "1 is 1" may or
>> may not return True.
>
>
> 'We' have not so agreed. The function should tell the truth. Let me repeat:
> 'is' is a function whose two inputs are not eternal mathematical values but
> rather are computational implementation objects with finite lifetimes.

Er, well, no. I'm willing to concede that I was wrong for being so
eager to say "y'all are wrong". I was, I misunderstood the objection
you and Steven were making, which is that "is" is well-defined, but
object identities are not.

However, you appear to be trying to shift the goalposts. Either "1 is
1" is always True, or always False, or sometimes one or the other. If
I'm mistaken and it so happens that numeric constants are guaranteed
somewhere to always be cached, then replace it with the empty tuple.
It is a fact that the result is not always the same, and you're trying
to dodge around that. :/

> It is wrong to interpret the Python expression '1 is 1' as a mathematical
> expression. It simply is not such. Trying to do so only leads to confusion,
> as this thread show.

Of course it's a mathematical expression. There's a very well
researched theory of computation that links Python all the way to
abstract purely-functional calculi, allowing us to mathematically
model everything.

But if you mean, "this isn't like high school arithmetic", sure. It
depends on a lot more than these things usually do (you say it depends
on time, but in the simple cases above, it depends on how number
objects and tuple objects are created.)

> The 'is' function answers a question about the current state of a particular
> temporal computational process. Its output is well-determined given its
> actual input. Like other introspection functions, it is useful for testing
> an implementation.

Sure, I understand this now. I am a bit regretful, the discussion of
whether "is" itself is ambiguous, or the actual values, doesn't really
matter. What matters is that sometimes "() is ()" will return True,
and sometimes it will return False. It doesn't really matter whether
it's "is" that's ambiguous, or the identity of newly made tuples. The
point is that something is ambiguous. And maybe that's worth changing?

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


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Devin Jeanpierre
On Mon, Apr 23, 2012 at 4:27 PM, Devin Jeanpierre
 wrote:
> Well, no. Immutable objects could always compare equal, for example.
> This is more expensive though. is as-it-stands is very quick to
> execute, which is probably attractive to some people (especially for
> its used in detecting special constants).

I don't know what made me write that so wrong. I meant "immutable
objects that are equal could always compare the same via is".

That makes 4 posts in a row. Sorry for the spam.

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


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Devin Jeanpierre
On Mon, Apr 23, 2012 at 4:06 PM, Terry Reedy  wrote:
>> The only way to check if two values are the same or not is to compare
>> via is or compare the return values of id().
>
> To quote you, 'bollocks'. The right way to compare values is with value
> comparison operators.

I meant "the same object".

>
>> So you can say that is or
>>
>> id() are ill-defined, or you can say that the identity of new numbers
>> is ill-defined,
>
>
> 'numbers' do not have identity, at least not separate from value.
> Concrete computational process objects do.

I meant "number objects".

I hope I did not cause any genuine confusion.

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


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Bernd Nawothnig
On 2012-04-23, Paul Rubin wrote:
> Kiuhnm  writes:
>> I can't think of a single case where 'is' is ill-defined.
>
> If I can't predict the output of 
>
> print (20+30 is 30+20)  # check whether addition is commutative
> print (20*30 is 30*20)  # check whether multiplication is commutative
>
> by just reading the language definition and the code, I'd have to say
> "is" is ill-defined.

"is" was never designed for comparing literals or expressions.

the expression 

20+30 is 30+20

maybe syntactically correct but is nevertheless pretty senseless and
you can, of course, not check commutativity with it.

For checking commutativity you have to use:

20+30 == 30+20

>
>> You're blaming 'is' for revealing what's really going on. 'is' is
>> /not/ implementation-dependent. It's /what's going on/ that's
>> implementation-dependent.
>> "a is b" is true iff 'a' and 'b' are the same object. Why should 'is'
>> lie to the user?
>
> Whether a and b are the same object is implementation-dependent.

>>> a = something
>>> b = a
>>> a is b
True

Should be guaranteed and implementation-independent.




Bernd

-- 
"Die Antisemiten vergeben es den Juden nicht, dass die Juden Geist
haben - und Geld." [Friedrich Nietzsche]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Tim Delaney
On 24 April 2012 06:40, Devin Jeanpierre  wrote:

> On Mon, Apr 23, 2012 at 4:27 PM, Devin Jeanpierre
>  wrote:
> > Well, no. Immutable objects could always compare equal, for example.
> > This is more expensive though. is as-it-stands is very quick to
> > execute, which is probably attractive to some people (especially for
> > its used in detecting special constants).
>
> I don't know what made me write that so wrong. I meant "immutable
> objects that are equal could always compare the same via is".
>

And doing that would make zero sense, because it directly contradicts the
whole *point* of "is". The point of "is" is to tell you whether or not two
references are to the same object. This is a *useful* property.

I'll leave aside the question of how you determine if an object is
immutable, and restrict the discussion to a few built-in types that are
known to be immutable.

If two objects are not the same object, then lying and saying they are
would remove the opportunity for various programming techniques, such as
interning. Of course, you could say that all immutable objects should be
interned automatically. There are a couple problems with this that I can
think of off the top of my head.

The first problem is memory. If every immutable object is interned then
welcome to the world of ever-expanding memory usage. Ah - but Python has
got around this for interned strings! They're ejected from the intern cache
when there are no more references. Surely we could do the same for integers
and other immutables?

That brings us to performance. You do not want computations involving
immutable objects to suffer severe performance degradation just to make
equal immutable objects have the same identity. But if every single step of
a numerical calculation involved the following sequence of possible steps,
that's exactly what you would be doing:

1. Calculate result;

2. Lookup result in integer intern cache (involves hash() and ==);
- unavoidable

3. Add result to integer intern cache (involves hash() and ==, and maybe
resizing the cache);
- necessary if your result is not currently referenced anywhere else in the
Python VM

4. Lookup previous intermediate result in integer intern
cache (involves hash() and ==);
- necessary if you have a previous intermediate result

5. Eject previous intermediate result from integer intern
cache (involves hash() and ==).
- necessary if you have a previous intermediate result that is not
currently referenced anywhere else in the Python VM

Now think of the Python implementation of any checksum algorithm. Nearly
every intermediate result (a reasonably-large hash) is not going to be used
anywhere else in the VM, and will require all 4 extra steps. Ouch.

Instead, CPython makes the (sensible) choice to intern heavily-used
integers permanently - (-5, 256) IIRC - and leaves the rest up to the
programmer.

Strings are a different question. Unlike integers, where == is cheap, ==
for strings can be prohibitively expensive. Consider the case that for
whatever reason you create a 1GB string. Now imagine creating or deleting a
reference to *any* string potentially involves calling == on the 1GB
string. Ouch again.

Instead, CPython makes the (sensible) choice to automatically intern short
strings that look like names (in the Python sense) and leave everything
else up to the programmer. It's possible for the programmer to manually
intern their 1GB string, but they've then got to deal with the consequences
of doing so.

Tim Delaney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Devin Jeanpierre
On Mon, Apr 23, 2012 at 6:26 PM, Tim Delaney
 wrote:
> And doing that would make zero sense, because it directly contradicts the
> whole *point* of "is". The point of "is" is to tell you whether or not two
> references are to the same object. This is a *useful* property.

It's useful for mutable objects, yes. How is it useful for immmutable
things? They behave identically everywhere where you don't directly
ask the question of "a is b" or "id(a) == id(b)". And whenever you ask
that question, the answer is an implementation detail: sometimes
equality implies "is", sometimes not, it depends on the values and the
implementation of Python, because the implementation is free to intern
liberally.

Therefore it shouldn't make any difference if we make equality
_always_ imply "is", since that was always on the table as an
implementation detail.

I think the real breakage is that now "a is b" is not equivalent to
"id(a) == id(b)" (unless you try to hack that as well.)

> I'll leave aside the question of how you determine if an object is
> immutable, and restrict the discussion to a few built-in types that are
> known to be immutable.

Right. This is what everyone does, when they implement this "modified
is" (e.g. ECMAScript Harmony's "is" operator works this way:
http://wiki.ecmascript.org/doku.php?id=harmony:egal ).

> If two objects are not the same object, then lying and saying they are would
> remove the opportunity for various programming techniques, such as
> interning. Of course, you could say that all immutable objects should be
> interned automatically. There are a couple problems with this that I can
> think of off the top of my head.

Hold up, why do we give up interning? As you mention later, interning
only involves hashing and equality comparisons, not id() or is. (e.g.
we can intern `y` just fine with `y = cache.setdefault(y, y)`)

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


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Tim Delaney
On 24 April 2012 09:08, Devin Jeanpierre  wrote:

> On Mon, Apr 23, 2012 at 6:26 PM, Tim Delaney
>  wrote:
> > And doing that would make zero sense, because it directly contradicts the
> > whole *point* of "is". The point of "is" is to tell you whether or not
> two
> > references are to the same object. This is a *useful* property.
>
> It's useful for mutable objects, yes. How is it useful for immmutable
> things? They behave identically everywhere where you don't directly
> ask the question of "a is b" or "id(a) == id(b)".


Not always. NaNs are an exception - they don't even compare equal to
themselves. And hence a very good reason why "is" and == are separate
operations.


> Therefore it shouldn't make any difference if we make equality
> _always_ imply "is", since that was always on the table as an
> implementation detail.
>

See above. Identity does not necessarily imply equality.


> I think the real breakage is that now "a is b" is not equivalent to
> "id(a) == id(b)" (unless you try to hack that as well.)


The operations are indeed equivalent if the lifetimes of both objects cover
the entire computation. Since you are not rebinding names here, there is no
way that the operations could not be equivalent (unless multithreading is
involved and the name bindings change underneath you, but I think we can
discount that for the purposes of this discussion).

There is no breakage here - just (I'm suspecting willful) lack of
understanding.

>>> a = "a"
>>> b = a
>>> a is b
True
>>> id(a) == id(b)
True
>>> a = "a"
>>> b = "b"
>>> a is b
False
>>> id(a) == id(b)
False

Absolutely consistent results. The fact that a Python implementation is
free to reuse IDs once that ID is no longer in use (the behaviour prompting
this thread in the first place) is irrelevant here. At no time will "a is
b" and "id(a) == id(b)" give inconsistent results when the names "a" and
"b" remain bound to the same objects across the comparisons.

> remove the opportunity for various programming techniques, such as
> > interning. Of course, you could say that all immutable objects should be
> > interned automatically. There are a couple problems with this that I can
> > think of off the top of my head.
>
> Hold up, why do we give up interning? As you mention later, interning
> only involves hashing and equality comparisons, not id() or is. (e.g.
> we can intern `y` just fine with `y = cache.setdefault(y, y)`)


I should now conclude that you have no interest in actually discussing this
but just want to take an obstinate position and never consider moving from
it.

But I'll give one last chance. What is the whole point of interning? It's
to get a canonical object to reference:

>>> a = "a " + "b"
>>> b = "a b"
>>> a is b
False
>>> a = intern(a)
>>> b = intern(b)
>>> a is b
True

For (most*) immutable objects, if there is only ever a single canonical
instance with that value, == and "is" are effectively the same operation
(what you seem to want). Python's types are implemented this way - they do
an "is" check before moving onto the more expensive equality check (except
where overridden*). That's the benefit. But as you will see if you go back
and read my message, there is a tradeoff in memory and/or performance
involved in the canonicalising. Somewhere between no canonicalising and
canonicalising everything (inclusive) is a sweet spot in terms of this
tradeoff, and it varies depending on other decisions that have been made
for the language and (of course) the actual program being run.

* NaNs again.

Tim Delaney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Robert Kern

On 4/24/12 1:03 AM, Tim Delaney wrote:

On 24 April 2012 09:08, Devin Jeanpierre mailto:jeanpierr...@gmail.com>> wrote:

On Mon, Apr 23, 2012 at 6:26 PM, Tim Delaney
mailto:timothy.c.dela...@gmail.com>> wrote:
 > And doing that would make zero sense, because it directly contradicts the
 > whole *point* of "is". The point of "is" is to tell you whether or not 
two
 > references are to the same object. This is a *useful* property.

It's useful for mutable objects, yes. How is it useful for immmutable
things? They behave identically everywhere where you don't directly
ask the question of "a is b" or "id(a) == id(b)".


Not always. NaNs are an exception - they don't even compare equal to themselves.
And hence a very good reason why "is" and == are separate operations.


I think you misread what Devin wrote. "id(a) == id(b)" not "a == b".

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Tim Delaney
On 24 April 2012 10:18, Robert Kern  wrote:

> On 4/24/12 1:03 AM, Tim Delaney wrote:
>
>> On 24 April 2012 09:08, Devin Jeanpierre > > wrote:
>>
>>On Mon, Apr 23, 2012 at 6:26 PM, Tim Delaney
>>> >
>> wrote:
>> > And doing that would make zero sense, because it directly
>> contradicts the
>> > whole *point* of "is". The point of "is" is to tell you whether or
>> not two
>> > references are to the same object. This is a *useful* property.
>>
>>It's useful for mutable objects, yes. How is it useful for immmutable
>>things? They behave identically everywhere where you don't directly
>>ask the question of "a is b" or "id(a) == id(b)".
>>
>>
>> Not always. NaNs are an exception - they don't even compare equal to
>> themselves.
>> And hence a very good reason why "is" and == are separate operations.
>>
>
> I think you misread what Devin wrote. "id(a) == id(b)" not "a == b".


No - I was addressing "they behave identically everywhere ..." in the
quote. NaNs are a case whre they do not behave identically everywhere.

Tim Delaney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Devin Jeanpierre
On Mon, Apr 23, 2012 at 8:03 PM, Tim Delaney
 wrote:
> On 24 April 2012 09:08, Devin Jeanpierre  wrote:
>>
>> On Mon, Apr 23, 2012 at 6:26 PM, Tim Delaney
>>  wrote:
>> > And doing that would make zero sense, because it directly contradicts
>> > the
>> > whole *point* of "is". The point of "is" is to tell you whether or not
>> > two
>> > references are to the same object. This is a *useful* property.
>>
>> It's useful for mutable objects, yes. How is it useful for immmutable
>> things? They behave identically everywhere where you don't directly
>> ask the question of "a is b" or "id(a) == id(b)".
>
>
> Not always. NaNs are an exception - they don't even compare equal to
> themselves. And hence a very good reason why "is" and == are separate
> operations.

You can't use "is": with NaNs any more than any other number.
Sometimes it does what you want, sometimes not, depending on whether
Python interns NaNs. The only real way to check if a value is NaN is
to use math.isnan. The differing behavior of == and "is" is _not_
reliable -- sometimes a is b will return False even though both a and
b are NaN.

There are systems under which "is" _would_ be reliable for this. I'm
not sure whether I'd want to argue for it, but I'm most of the way
anyway. You would have to either intern all NaNs, or else change the
definition of "is".



Also, when I say "two things behave identically everywhere", I mean
that we have two objects, `a` and `b`, such that for any function f(),
you'd have the exact same effects of your program called f(a) or f(b)
in the same place.

(This is addressed in the following page:
http://home.pipeline.com/~hbaker1/ObjectIdentity.html )

There is no way to observe any difference between immutable values
that are equal except via id() and the is operator. They are equal,
and they will never stop being equal. Presumably equality is designed
sanely so that they have the same structure, so iteration etc. all
have the same results. There is no way to distinguish them based on
any of their properties, except to resort to the is operator and id()
function.

This is not true of mutable values. For example, consider the following program:

a = []
b = c = []
c.append(3)
print b

a and c cannot be completely identical, because if we replaced
"c.append(3)" with "a.append(3)", the print at the bottom would have a
different outcome. No such difference can ever occur with immutable
objects (modulo some technical details if you really want to get
picky, and also id and is).

So, to address NaNs: if you have a, and a is a NaN, and so is b --
what program would behave differently if you swapped a and b? how do
you tell them apart?

My assertion from before is that they behave identically -- they
behave the same way -- everywhere where you don't directly ask the
question of "a is b" or "id(a) == id(b)".

>>
>> Therefore it shouldn't make any difference if we make equality
>> _always_ imply "is", since that was always on the table as an
>> implementation detail.
>
>
> See above. Identity does not necessarily imply equality.

You have the implication backwards. I was saying that, for immutable
objects, perhaps equality should imply identity. I was furthermore
justifying this by saying that it wouldn't break anything that wasn't
already broken. i.e., the only things that would be broken were the
things that didn't remember that Python can intern immutable objects.

>>
>> I think the real breakage is that now "a is b" is not equivalent to
>> "id(a) == id(b)" (unless you try to hack that as well.)
>
>
> The operations are indeed equivalent if the lifetimes of both objects cover
> the entire computation. Since you are not rebinding names here, there is no
> way that the operations could not be equivalent (unless multithreading is
> involved and the name bindings change underneath you, but I think we can
> discount that for the purposes of this discussion).
>
> There is no breakage here - just (I'm suspecting willful) lack of
> understanding.

It's you that doesn't understand. Perhaps it is willful lack of
understanding? ;)

I was discussing what happens if you change "is" such that "a is b" in
all current situations, plus the situations where a and b are
immutable and equal.

The email you originally sent was in response to one in which I change
the way "is" works, and you had a complaint against that change. In
response, I said that I don't think the complaint is a good one, but I
suggested one other complaint. Under the change that I suggested,
id(a) == id(b) would no longer be equivalent to a is b, because `a is
b` can be true even for objects in different places in memory.

I think, in that context, a lot of what you say probably doesn't make
sense the way you meant it to, but I'll address it anyway.

> I should now conclude that you have no interest in actually discussing this
> but just want to take an obstinate position and never consider moving from
> it.

There are two situations. In one, I'm a troll, 

Re: This code not working, need suggetions

2012-04-23 Thread Anirudh Srinivasan
Thanks Min and Chris for your ideas and suggestion, i understood my
mistake. This code is working fine now.

On Mon, Apr 23, 2012 at 2:51 AM, Min Yu  wrote:

> try this code out. The lsdir function and cat function are both used in
> main().
>
> The bash commands are as following:
>
> yumin@yumin-think:~/src/test/python/community$ python list.py `pwd`
> /home/yumin/src/test/python/community
> list.py
> file1
> file2
> Which file would you like to browse ?file1
> This is file1
> Which file would you like to browse ?file2
> This is file2
>
> Which file would you like to browse ?
> yumin@yumin-think:~/src/test/python/community$
>
> --
>
> #!/usr/bin/python
>
>
> import os
> import sys
> import commands
> #import cat
>
> def listdir(s):
> try:
> print s
> files  = os.listdir(s)
> for f in files:
> #path = os.path.join(s, f)
> #print path
> print f
>
> except OSError:
> print "No such file or directory"
>
> def cat(get_file):
> f = open(get_file, "rU")
> text = f.read()
> print text,
>
> def main():
> working_dir = sys.argv[1]
> listdir(working_dir)
> On = True
> while On:
> get_file = raw_input("Which file would you like to browse ?")
> if get_file == '':
> On = False
> #break
> else:
> cat(os.path.join(working_dir,get_file))
>
>
> if __name__ == "__main__":
> main()
>
>
>
> 2012/4/23 Chris Rebert 
>
>> On Sun, Apr 22, 2012 at 11:16 PM, Anirudh Srinivasan > >
>> wrote:
>> >
>> > My code lists the files and directory under a folder and if we want to
>> > read the file it uses the function  cat.
>> >
>> > But the function cat(get_file) is not working , any suggetions?
>>
>> Please specifically state exactly how it's deviating from the desired
>> behavior (including the full text of any error messages and/or
>> exception tracebacks, though I don't think those will apply here).
>> I note that you don't actually call cat() anywhere in your program.
>>
>> > Here is my code:
>> >
>> >
>> > #!/usr/bin/python
>> >
>> > import os
>> > import sys
>> > import commands
>> > #import cat
>>
>> Such an import (if uncommented) would require you had a *module* named
>> `cat`.
>>
>> > def listdir(s):
>>
>> I would suggest renaming this function to avoid confusion with
>> os.listdir().
>>
>> >try:
>> >   file  = os.listdir(s)
>>
>> Don't use `file` as a variable name. It shadows the name of the
>> built-in `file` type.
>> Also, `file` isn't a sensible variable name in this context; it's a
>> list (as opposed to a single item) and may also contain directory
>> names. And it contains strings rather than file objects.
>>
>> >   for files in file:
>> >   path = os.path.join(s, files)
>> >   print path
>> >   #cmd = 'ls -l '+ path
>> >   #g= commands.getstatusoutput(cmd)
>>
>> The `commands` module has been deprecated. Its successor is `subprocess`:
>> http://docs.python.org/library/subprocess.html
>>
>> >   #print g[1]
>> >except OSError:
>> >   print "No such file or directory"
>> >
>> >
>> > def main():
>> >   listdir(sys.argv[1])
>> >
>> >
>> > if __name__ == "__main__":
>> >   main()
>>
>> `if __name__ == "__main__":` should normally come at the end of the
>> script, after all `def`s.
>>
>> >
>> > def cat(get_file):
>> >   f = open(get_file, "rU")
>> >   text = f.read()
>> >   print text,
>>
>> You should `.close()` the file once you're done with it. Or use the
>> `with` statement (http://www.python.org/dev/peps/pep-0343/ ).
>>
>> > get_file = raw_input("Which file would you like to browse ?")
>>
>> Presumably this line should be under your `if __name__ ==
>> "__main__":`? And you're not actually doing anything with `get_file`
>> after you obtain it from the user...
>>
>> Regards,
>> Chris
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>


-- 
Anirudh Srinivasan | MTS QA | Nutanix.Inc | 408-569-0323
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Tim Delaney
On 24 April 2012 11:08, Devin Jeanpierre  wrote:

> cache = {}
>
> def intern(x):
> return cache.setdefault(x, x)
>
> Do we agree that A) this function works without using identity
> comparisons, and B) this function performs the task of interning?


Of course. I never claimed otherwise. It is however returning a reference
to a canonical object equal to the object being referred to by "x". In this
case, the canonical/standard form is "the first equal object that was put
into the cache".

cache = {}

def intern(x):
return cache.setdefault(x, x)

>>> a = "x y"
>>> b = "x y"
>>> a is b
False
>>> id(a) == id(b)
False
>>> a = intern(a)
>>> b = intern(b)
>>> a is b
True
>>> id(a) == id(b)
True

My claim is that doing this automatically for all integers and/or strings
could lead to prohibitively-expensive performance characteristics, and done
wrong to prohibitively-expensive memory characteristics.

Now, you could declare "is" and == as the same operation for a whitelist of
types, but people have actual uses for being able to distinguish different
instances of equal immutable types. You shouldn't need to do it in your
normal day-to-day programming, but there are real uses for it.

cache = {}
> cachednan = float('nan')
>
> def intern(x):
>try:
>if math.isnan(x):
>return cachednan
>except TypeError:
>pass
>return cache.setdefault(x, x)
>
> I hope, again, that I've demonstrated that we don't need to
> canonicalize everything just to implement interning.


Except that the above is a canonicalisation function.

Tim Delaney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Devin Jeanpierre
On Mon, Apr 23, 2012 at 11:03 PM, Tim Delaney
 wrote:
> My claim is that doing this automatically for all integers and/or strings
> could lead to prohibitively-expensive performance characteristics, and done
> wrong to prohibitively-expensive memory characteristics.

OK. I agree, and I'm not in favor of doing that. It's a nice
optimization, there's no point doing it in cases where it leads to
_worse_ performance.

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



Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Terry Reedy

On 4/23/2012 4:37 PM, Devin Jeanpierre wrote:


However, you appear to be trying to shift the goalposts. Either "1 is
1" is always True, or always False, or sometimes one or the other. If
I'm mistaken and it so happens that numeric constants are guaranteed
somewhere to always be cached, then replace it with the empty tuple.
It is a fact that the result is not always the same,


The result is always the current truth of the matter.


and you're trying to dodge around that. :/


In a previous post you chided Stephen for an ad hominem comment. Above 
you make two. Both are false. I am insisting that Python's 'is' should 
be judged as what it is, which is a non-mathematical introspection 
function. And I am hardly dodging around something I have understood and 
been telling and warning people about on comp.lang.python and thisn list 
for 15 years. That is a nasty lie.



It is wrong to interpret the Python expression '1 is 1' as a mathematical
expression. It simply is not such. Trying to do so only leads to confusion,
as this thread show.


Of course it's a mathematical expression.


Bollocks. It is a question about a non-mathematical* fact of 'the 
world', which is a Python computing session.

* As I understand the adjective 'mathematical'.

Consider the expression 'Bob is Robert'. If it means "The string 'Bob' 
is the string 'Robert'" then is would be a mathematical expression of 
string theory and the answer would be False. If it means "The person 
connected with the name 'Bob' at this time in the currect context is the 
same person connected with 'Robert'", then it is not a mathematical 
question but is contingent# on the facts of the world.


# Contingency is not ambiguity.

Anyway, I think I am done with this thread.

--
Terry Jan Reedy

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


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread Devin Jeanpierre
On Tue, Apr 24, 2012 at 12:12 AM, Terry Reedy  wrote:
>> and you're trying to dodge around that. :/
>
> In a previous post you chided Stephen for an ad hominem comment. Above you
> make two. Both are false.

I accused you of not answering the question or shifting goalposts.
This is an attack against your response, not an attack against you
("ad hominem" literally means "to the person").

Also, I definitely tried to lighten that one up with a classy
emoticon. It's totally not fair that you're scoring points off it.

> Anyway, I think I am done with this thread.

... Good idea.

We clearly understand Python's behavior. I just spent the whole time
bickering about definitions. Ugh. I'm an idiot. Sorry for the trouble.

-- Devin

(P.S. can we all start saying "muppet" next?)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why () is () and [] is [] work in other way?

2012-04-23 Thread rusi
On Apr 23, 9:34 am, Steven D'Aprano  wrote:

> "is" is never ill-defined. "is" always, without exception, returns True
> if the two operands are the same object, and False if they are not. This
> is literally the simplest operator in Python.

Circular definition: In case you did not notice, 'is' and 'are' are
(or is it is?) the same verb.
-- 
http://mail.python.org/mailman/listinfo/python-list