Re: checking if a list is empty

2011-05-12 Thread Ben Finney
Hans Georg Schaathun  writes:

> On Wed, 11 May 2011 20:31:45 -0700 (PDT), alex23
>wrote:
> :  On May 12, 7:24 am, harrismh777  wrote:
> : > We need to move away from 'canned apps' to a new day where
> : > the masses can sit down to their computer and solve new problems with it
> : > through intuitive language skills.  Why not?
> : 
> :  Because the vast majority of them don't seem to want to be bothered?
>
> Why does that matter?  There is a sizeable group who need computers
> for purposes not (sufficiently) supported by the `canned apps'.

Those people, outnumbered by the masses as you say, are thereby not
themselves “the masses”.

-- 
 \  “Hey Homer! You're late for English!” “Pff! English, who needs |
  `\  that? I'm never going to England!” —Barney & Homer, _The |
_o__)Simpsons_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-12 Thread Hans Georg Schaathun
On Thu, 12 May 2011 16:46:38 +1000, Ben Finney
   wrote:
:  Hans Georg Schaathun  writes:
: 
: > On Wed, 11 May 2011 20:31:45 -0700 (PDT), alex23
: >wrote:
: > :  On May 12, 7:24 am, harrismh777  wrote:
: > : > We need to move away from 'canned apps' to a new day where
: > : > the masses can sit down to their computer and solve new problems with it
: > : > through intuitive language skills.  Why not?
: > : 
: > :  Because the vast majority of them don't seem to want to be bothered?
:  >
: > Why does that matter?  There is a sizeable group who need computers
: > for purposes not (sufficiently) supported by the `canned apps'.
: 
:  Those people, outnumbered by the masses as you say, are thereby not
:  themselves “the masses”.

So what?  Do we only need solutions and systems for the masses?

What about systems for those who develop systems for the masses?
Or the theory necessary to develop the systems to develop more
advanced systems for the masses in the future?

Get real, software development and programming is more than just
overpriced web systems that just almost manage to replicate the 
functionality of IBM page based terminals and mainframes of 1973,
just slower and with more eye candy.

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


Re: checking if a list is empty

2011-05-12 Thread Ben Finney
Hans Georg Schaathun  writes:

> On Thu, 12 May 2011 16:46:38 +1000, Ben Finney
>wrote:
> :  Hans Georg Schaathun  writes:
> : 
> : > On Wed, 11 May 2011 20:31:45 -0700 (PDT), alex23
> : >wrote:
> : > :  On May 12, 7:24 am, harrismh777  wrote:
> : > : > We need to move away from 'canned apps' to a new day where
> : > : > the masses can sit down to their computer and solve new problems with 
> it
> : > : > through intuitive language skills.  Why not?
> : > : 
> : > :  Because the vast majority of them don't seem to want to be bothered?
> :  >
> : > Why does that matter?  There is a sizeable group who need computers
> : > for purposes not (sufficiently) supported by the `canned apps'.
> : 
> :  Those people, outnumbered by the masses as you say, are thereby not
> :  themselves “the masses”.
>
> So what?  Do we only need solutions and systems for the masses?

Your “why does that matter?” was addressed to an answer specifically in
the context of “a new day where the masses can sit down to their
computer and …”. The question is asked and answered.

If you want to raise a *new* topic – that of the non-masses who have
different needs – it's best not to start with “Why does that matter?”
but to lay out your separate case.

-- 
 \“Visitors are expected to complain at the office between the |
  `\ hours of 9 and 11 a.m. daily.” —hotel, Athens |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Developers with 5 years of experience

2011-05-12 Thread John Nagle

On 5/4/2011 10:32 AM, Jerome jjcpl.rpo wrote:

send resumes to [email protected]


One of our client in New Jersey is looking for Python Developers with
5 years of experience.   If you have any resumes please send it
across.


   Very strange recruiting organization.  Strong Christian
religious orientation, but run from India.

"He who trusts in the LORD will be prospered ! Proverb 28:25"

"JEHOVAH JIREH COMMUNICATIONS is promoted by a group of professionals 
with extensive IT experience, especially in the Staffing Industry, 
across the globe."


Headoffice
Plot No 158, CGE Colony
First Street
Tuticorin - 628003
Tamilnadu
Phone no: 91 461 4005333 / 3290473
Fax No: 91 461 4001473
Email : [email protected]

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


Re: unicode by default

2011-05-12 Thread John Machin
On Thu, May 12, 2011 4:31 pm, harrismh777 wrote:

>
> So, the UTF-16 UTF-32 is INTERNAL only, for Python

NO. See one of my previous messages. UTF-16 and UTF-32, like UTF-8 are
encodings for the EXTERNAL representation of Unicode characters in byte
streams.

> I also was not aware that UTF-8 chars could be up to six(6) byes long
> from left to right.

It could be, once upon a time in ISO faerieland, when it was thought that
Unicode could grow to 2**32 codepoints. However ISO and the Unicode
consortium have agreed that 17 planes is the utter max, and accordingly a
valid UTF-8 byte sequence can be no longer than 4 bytes ... see below

>>> chr(17 * 65536)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: chr() arg not in range(0x11)
>>> chr(17 * 65536 - 1)
'\U0010'
>>> _.encode('utf8')
b'\xf4\x8f\xbf\xbf'
>>> b'\xf5\x8f\xbf\xbf'.decode('utf8')
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\python32\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xf5 in position 0:
invalid start byte


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


Re: lightweight way to create new projects from templates

2011-05-12 Thread Jonathan Hartley
Hey Chris,

Thanks for the thoughts. I must confess I had already given up on a 'single 
file' approach, because I want to make it easy for people to create their own 
templates, so I have to handle copying a template defined by creating a new 
directory full of diles. If I'm already handling this case, I thought, I might 
as well bundle the built-in default templates as a bunch of files.

I'd hope to provide platform binaries to make download and install easy for 
end-users, regardless of what Python version they already have installed.

Which reminds me, I should make sure the default template works on Python2.x as 
well as 3.x. Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib2 request with binary file as payload

2011-05-12 Thread Michiel Sikma
>
> 2.6 is expecting a string, according to the above. No mention of file.
> Moreover it expects the data to be urlencoded. 2.7.1 docs say the same
> thing. Are you sure you have shown the code that worked with 2.6?
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Yes, in fact I simply tried passing the file to the Request class
without having checked the docs to see if I could even do that, but it
worked. I also send an unencoded XML string a little bit earlier on.
Maybe it no longer needs to be a urlencoded string as soon as you add
a Content-Type header.

Here's what happens when I put the HTTPHandler in debug mode and pass
a file in 2.6:

send: 'PUT 
/resumable/feeds/api/users/default/uploads?upload_id=[id]HTTP/1.1\r\nAccept-Encoding:
identity\r\nContent-Length: 898801\r\nHost:
uploads.gdata.youtube.com\r\nContent-Type:
application/octet-stream\r\nConnection: close\r\nUser-Agent:
Python-urllib/2.6\r\n\r\n'
send: 
sendIng a read()able

A little while later:

reply: 'HTTP/1.1 201 Created\r\n'
[...etc]

So it seems to work just fine, but 2.5 does indeed complain about this
being an incorrect use of Request.

Moreover, though I can't upgrade my Python from 2.5 I was able to
compile another alongside it (latest stable 2.7) and use that with my
code, and it worked just fine. Uploaded a 6GB file to Youtube this
way. :)

Michiel Sikma
We Demand HTML

http://wedemandhtml.com/
[email protected]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: NewBie Doubt in Python Thread Programming

2011-05-12 Thread Chris Angelico
On Thu, May 12, 2011 at 3:35 PM, vijay swaminathan  wrote:
> I tried using QThread as well.. But the problem is, on the run method when i
> invoke the command prompt, it sends out the finished signal...  I want it to
> send out the finished signal only on closing the command prompt that is
> invoked earlier in my process.

>     subprocess.call(["start", "/DC:\\PerfLocal_PAL",
> "scripts_to_execute.bat"], shell=True)

This is your problem, still. You need to change to a call that waits.
In my testing on Windows (Python 2.6.5), this can be done with
os.system() quite happily. Change that, and it should all work.

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


Re: NewBie Doubt in Python Thread Programming

2011-05-12 Thread vijay swaminathan
Hi Chris,

I tried using os.system as well but it did not even open up the command
prompt.

Can you please share the code that worked for you.. just wondering if I'm
missing something very basic.

Regards,
-Vijay Swaminathan.,

On Thu, May 12, 2011 at 1:38 PM, Chris Angelico  wrote:

> On Thu, May 12, 2011 at 3:35 PM, vijay swaminathan 
> wrote:
> > I tried using QThread as well.. But the problem is, on the run method
> when i
> > invoke the command prompt, it sends out the finished signal...  I want it
> to
> > send out the finished signal only on closing the command prompt that is
> > invoked earlier in my process.
>
> > subprocess.call(["start", "/DC:\\PerfLocal_PAL",
> > "scripts_to_execute.bat"], shell=True)
>
> This is your problem, still. You need to change to a call that waits.
> In my testing on Windows (Python 2.6.5), this can be done with
> os.system() quite happily. Change that, and it should all work.
>
> Chris Angelico
> --
>  http://mail.python.org/mailman/listinfo/python-list
>



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


Re: Need Assistance on this program.

2011-05-12 Thread vijay swaminathan
I tried using that as well.

The problem is, the thread becomes dead as soon as it executes the
invocation of command prompt.

I want the thread to be alive till I go and manually close the command
prompt.

-Vijay Swaminathan.
On Thu, May 12, 2011 at 2:46 PM, Andrea Crotti wrote:

>  vijay swaminathan  writes:
>
> > Hi All,
> >
> > I'm new bie to python thread programming and would like to assistance
> > on the attached code.
> >
> > In this, I'm calling a thread to invoke a command prompt and would
> > like to print the "Thread as alive" as long as the command prompt is
> > opened and would like to print "Thread is Dead" only when the command
> > prompt is closed by the user.
> >
> > based on my understand I have written this peace of code which does
> > not seem to work. There is some flaw in the logic which I could not
> > understand since I'm not that familiar with the thread concepts.
> >
> > Can somebody help me in getting this piece of code working.
> >
> > Also can somebody point me to a good tutorial on understanding python
> > thread programming since I want to get my understanding on the concept
> > of thread better. I googled a few but quite confusing.
> >
> > --
> > Vijay Swaminathan
>
> Easy mistake, this:
>  if mythread_object.is_alive:
>
> is wrong, since is_alive is a method, not a bool so it should be
> is_alive().
>
> Pay attention to these things, and actually something called
> "is_adjective" is almost never a variable.
>



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


Re: Need Assistance on this program.

2011-05-12 Thread Andrea Crotti
vijay swaminathan  writes:

> Hi All,
>
> I'm new bie to python thread programming and would like to assistance
> on the attached code.
>
> In this, I'm calling a thread to invoke a command prompt and would
> like to print the "Thread as alive" as long as the command prompt is
> opened and would like to print "Thread is Dead" only when the command
> prompt is closed by the user.
>
> based on my understand I have written this peace of code which does
> not seem to work. There is some flaw in the logic which I could not
> understand since I'm not that familiar with the thread concepts.
>
> Can somebody help me in getting this piece of code working.
>
> Also can somebody point me to a good tutorial on understanding python
> thread programming since I want to get my understanding on the concept
> of thread better. I googled a few but quite confusing.
>
> -- 
> Vijay Swaminathan

Easy mistake, this:
  if mythread_object.is_alive:

is wrong, since is_alive is a method, not a bool so it should be
is_alive().

Pay attention to these things, and actually something called
"is_adjective" is almost never a variable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need Assistance on this program.

2011-05-12 Thread Tim Golden

On 12/05/2011 10:45, vijay swaminathan wrote:


I tried using that as well.
The problem is, the thread becomes dead as soon as it executes the
invocation of command prompt.


Can you post the code you're using, please?

This should be simple so maybe you've misunderstood
something in the threading / subprocess mix.

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


Re: Need Assistance on this program.

2011-05-12 Thread vijay swaminathan
Hi Tim,

I have already done that. But for some reason my response went as a new
thread. Attaching the code again.
On Thu, May 12, 2011 at 3:38 PM, Tim Golden  wrote:

> On 12/05/2011 10:45, vijay swaminathan wrote:
>
>>
>> I tried using that as well.
>> The problem is, the thread becomes dead as soon as it executes the
>> invocation of command prompt.
>>
>
> Can you post the code you're using, please?
>
> This should be simple so maybe you've misunderstood
> something in the threading / subprocess mix.
>
> TJG
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Vijay Swaminathan


Thread_Example1.py
Description: Binary data
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need Assistance on this program.

2011-05-12 Thread Tim Golden

On 12/05/2011 11:29, vijay swaminathan wrote:

<... snippet from code ...>
  print 'Invoking Command Promptt..'
#subprocess.call(["start", "/DC:\\PerfLocal_PAL", 
"scripts_to_execute.bat"], shell=True)
subprocess.call(["start", "C:\\windows\\system32\\cmd.exe"], 
shell = True)

self.status()


If you want to use start, use start /wait.

But you don't have to:


import threading
import time
import subprocess

def run_command (command):
  #
  # .call is shorthand for: start process and wait
  # CREATE_NEW_CONSOLE prevents it from getting messed
  #  up with the Python console
  #
  subprocess.call (
[command],
creationflags=subprocess.CREATE_NEW_CONSOLE
  )

t = threading.Thread (target=run_command, args=("cmd.exe",))
t.start ()

while t.is_alive ():
  print "alive"
  time.sleep (0.5)

print "Thread is dead"



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


Re: NewBie Doubt in Python Thread Programming

2011-05-12 Thread Chris Angelico
On Thu, May 12, 2011 at 7:42 PM, vijay swaminathan  wrote:
> Hi Chris,
>
> I tried using os.system as well but it did not even open up the command
> prompt.
>
> Can you please share the code that worked for you.. just wondering if I'm
> missing something very basic.

Caveat: I'm not using Qt, I just tried this in IDLE (which is graphical).

C:\>copy con test.bat
echo Hello, world!
pause
^Z
1 file(s) copied.


IDLE 2.6.5
>>> import os
>>> os.system("c:\\test.bat")
0

The 0 and subsequent prompt don't appear until the batch file
finishes. Meanwhile, the batch file is executing in a separate window.

When you try it inside Qt, do you get a background window that needs
to be brought to the front? Does execution pause while the batch file
runs?

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


Slice implementation bug

2011-05-12 Thread Tambet
Hello!

Let's say slice is multidimensional now - how to interpret it?

I excpect these to work:

   - m[0, 3] - get one element from matrix
   - m[0:2, 0:2] - get four elements from matrix, iterate over them (I have
   actually an rtree if it doesn't make sense to you)

But it won't, because if m[0, 3] returns something, then m[0:2, 0:2] cannot
yield anymore. Ofcourse I could return an iterator, but this would not be so
simple.

So, maybe we need these:

   - __isslice__(key) - return true, false
   - __getitem__(key) - return a value
   - __getslice__(key) - yield a lots of values

So that if isslice returns true, getslice will be called. Would be much more
beauty! Right now it's ugly. I love Python, but I also love n-dimensional
spaces and those are ugly in Python - last time I did Matrix multiplication
I could not implement m[0, 3] (stupid errors), could not m[0j + 3], could
not use tuple. Now I was happy that it's implemented and just ran into
another problem that I have to choose, if getter returns one or many :)
Ofcourse I could return list or other iterable, but I want to be able to do
it with three-liner, because the rest of my code mostly consists of those.
Except the few masterfunctions, which do some complex manipulations with
data.

I also need to implement things like that, which also return true for
__isslice__:
m[Circle(0, 0, 10)] - for RTree, any shape object implementing getExtent and
doesOverlap can be used as slice index.

Because I do complex map transformations and all this trivial stuff must be
*hidden*!

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


Re: checking if a list is empty

2011-05-12 Thread Roy Smith
In article <[email protected]>,
 Gregory Ewing  wrote:

> Roy Smith wrote:
> >>If both are numbers, they are converted to a common type. Otherwise, 
> >>objects of different types always compare unequal
> 
> That's just the default treatment for unrelated types that don't
> know anything about each other.
> 
> I would guess that the list's == method is asking "Is the
> other object a list?", and since a subclass of list is also
> a list, it's happy and goes on to compare the elements.

Well, that explains what's happening, but the behavior still doesn't 
match the docs.  Is this a bug or are the docs wrong?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Slice implementation bug

2011-05-12 Thread Andrea Crotti
Tambet  writes:

> Hello!
>
> Let's say slice is multidimensional now - how to interpret it?
>

But who said that slice is multidimensional in the first place?

Since python is not matlab I don't think it will ever be done, so what's
the purpose of talking about a bug in something that doesn't exist?

PS. probably in numpy you can find what you look for
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-12 Thread Chris Angelico
On Thu, May 12, 2011 at 4:21 PM, Hans Georg Schaathun  
wrote:
> On Thu, 12 May 2011 01:49:05 -0400, D'Arcy J.M. Cain
>   wrote:
> :  That's not programming.  That's using a canned app that a programmer
> :  wrote that takes your unstructured input and does something useful with
> :  it.  Spreadsheets are a primitive example of that.  Google is a more
> :  advanced example.
>
> You are really trying to defend the programmers' status as a modern
> day priesthood, mastering a mystic art completely inaccessible to
> those not initiated.

Anyone can join. Not everyone wants to join. Me, I'm happy here as a
priest of the software industry, and I have no desire to become a
priest of, say, automotive engineering or concrete pouring. Would an
expert concreter be expected to explain to me exactly how to make
different sorts of concrete, or would he be expected simply to fulfill
his contract and provide me with my structure?

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


list equal to subclass of list?

2011-05-12 Thread Roy Smith
I have a vague feeling this may have been discussed a long time ago, but 
I can't find the thread, so I'll bring it up again.

I recently observed in the "checking if a list is empty" thread that a 
list and a subclass of list can compare equal:


class MyList(list):
"I'm a subclass"

l1 = []
l2 = MyList()

print type(l1), type(l2)
print type(l1) == type(l2)
print l1 == l2


when run, prints:

 
False
True

The docs say:

[http://docs.python.org/library/stdtypes.html]
Objects of different types, except different numeric types and different 
string types, never compare equal

[http://docs.python.org/release/2.7/reference/expressions.html#notin]
objects of different types (emphasis)always compare unequal

In the test code above, l1 an l2 are different types, at least in the 
sense that type() returns something different for each of them.  What's 
the intended behavior here?  Either the code is wrong or the docs are 
wrong.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode by default

2011-05-12 Thread TheSaint
John Machin wrote:

> On Thu, May 12, 2011 2:14 pm, Benjamin Kaplan wrote:
>>
>> If the file you're writing to doesn't specify an encoding, Python will
>> default to locale.getdefaultencoding(),
> 
> No such attribute. Perhaps you mean locale.getpreferredencoding()

what about sys.getfilesystemencoding()
In the event to distribuite a program how to guess which encoding will the 
user has?


-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-12 Thread Hans Georg Schaathun
On Thu, 12 May 2011 22:16:10 +1000, Chris Angelico
   wrote:
:  Anyone can join. Not everyone wants to join. Me, I'm happy here as a
:  priest of the software industry, and I have no desire to become a
:  priest of, say, automotive engineering or concrete pouring. Would an
:  expert concreter be expected to explain to me exactly how to make
:  different sorts of concrete, or would he be expected simply to fulfill
:  his contract and provide me with my structure?

Of course he would.  When a piece of software to calculate the
properties or recipes for different kinds of concrete is needed.

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


generate properties code in class dynamically

2011-05-12 Thread JamesEM
Hello,
I have a python class that contains a dictionary.
I would like to use python properties to access the elements of the
dictionary.
This could be achieved as follows:

class MyClass(object):

def __init__(self):
self.d = {}
d['field1'] = 1.0
d['field2'] = 'A'
d['field3'] = [10.0,20.0,30.0]

@property
def field1(self):
return self.d['field1']

@field1.setter
def field1(self, value):
self.d['field1'] = value

@field1.deleter
def field1(self):
del self.d['field1']

@property
def field2(self):
return self.d['field2']

@field1.setter
def field2(self, value):
self.d['field2'] = value

@field1.deleter
def field2(self):
del self.d['field2']

@property
def field3(self):
return self.d['field3']

@field3.setter
def field3(self, value):
self.d['field3'] = value

@field3.deleter
def field3(self):
del self.d['field3']


However, I am effectively writing the same properties code three
times.
I would prefer to generate the properties code dynamically from the
keys of the dictionaries.
What I am looking for is something like:

class MyClass(object):

def __init__(self):
self.d = {}
d['field1'] = 1.0
d['field2'] = 'A'
d['field3'] = [10.0,20.0,30.0]
for f in d:
   create_property(f)


where create_property(f) dynamically creates the property code for
field f in MyClass.

Is this possible?
If so, how could I do it?

Thanks,
James
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-12 Thread Chris Angelico
On Thu, May 12, 2011 at 10:43 PM, Hans Georg Schaathun  
wrote:
> On Thu, 12 May 2011 22:16:10 +1000, Chris Angelico
>   wrote:
> :  Anyone can join. Not everyone wants to join. Me, I'm happy here as a
> :  priest of the software industry, and I have no desire to become a
> :  priest of, say, automotive engineering or concrete pouring. Would an
> :  expert concreter be expected to explain to me exactly how to make
> :  different sorts of concrete, or would he be expected simply to fulfill
> :  his contract and provide me with my structure?
>
> Of course he would.  When a piece of software to calculate the
> properties or recipes for different kinds of concrete is needed.

Writing a program requires expertise both in programming and in the
purpose for which it's being written. Ultimately, a programmer is a
translator; without proper comprehension of the material he's
translating, he can't make a clear translation. But that's completely
different from hiring someone to do a job, and then looking at the job
afterwards; if I order a concreting job, I'll look at whether it's
properly suited to the task, but I won't expect an explanation of
exactly what went into it, and I do not expect to understand the exact
chemistry of it. Only another expert in concrete would truly
comprehend it all.

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


Re: py3k buffered IO - flush() required between read/write?

2011-05-12 Thread Genstein

With 3.2 on winxp, that is what I get with StringIO, text file, and
bytes file (the first two with b's removed). I would expect the same on
any system. If you get anything different, I would consider it a bug


Thanks Terry, you're entirely right there; I trimmed down my test case, 
asked for confirmation and have reported it as 
http://bugs.python.org/issue12062. Noted here in case anyone else trips 
over it.

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


Customize help output from optparse (or argparse)

2011-05-12 Thread Thorsten Kampe
Hi, 

I'm using optparse for a little Python script.

1. The output from "--help" is:
"""
Usage: script.py 

script.py does something

Options:
  -h, --help   show this help message and exit
"""

I would prefer to have the description before the usage, like...
"""
script.py does something

Usage: script.py 

Options:
  -h, --help   show this help message and exit
"""

2. The output from "--doesnotexit" is:
"""
Usage: script.py 

script.py: error: no such option: --doesnotexist
"""

I would prefer to have the error first, then the usage and additionally 
the options, like...
"""
script.py: error: no such option: --doesnotexist

Usage: script.py 

Options:
  -h, --help   show this help message and exit
"""

Is that possible with either optparse or the "new kid on the block" 
argparse. If so how?

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


Re: list equal to subclass of list?

2011-05-12 Thread Algis Kabaila
On Thursday 12 May 2011 22:23:04 Roy Smith wrote:
> I have a vague feeling this may have been discussed a long
> time ago, but I can't find the thread, so I'll bring it up
> again.
> 
> I recently observed in the "checking if a list is empty"
> thread that a list and a subclass of list can compare equal:
> 
> 
> class MyList(list):
> "I'm a subclass"
> 
> l1 = []
> l2 = MyList()
> 
> print type(l1), type(l2)
> print type(l1) == type(l2)
> print l1 == l2
> 
> 
> when run, prints:
> 
>  
> False
> True
> 
> The docs say:
> 
> [http://docs.python.org/library/stdtypes.html]
> Objects of different types, except different numeric types
> and different string types, never compare equal
> 
> [http://docs.python.org/release/2.7/reference/expressions.htm
> l#notin] objects of different types (emphasis)always compare
> unequal
> 
> In the test code above, l1 an l2 are different types, at
> least in the sense that type() returns something different
> for each of them.  What's the intended behavior here? 
> Either the code is wrong or the docs are wrong.

Subclassing of lists can be tricky, as you have indicated. Here 
is another simple example:

Using Python 3.2,

>>> class Array(list):
def __init__(self):
print(type(self))
temp = [[0,0], [0,0]]
print('temp =', temp)
self = temp[:]
print(type(self), type(temp))
print('self =', self)
>>> a = Array()

temp = [[0, 0], [0, 0]]
 
self = [[0, 0], [0, 0]]

So copying *values* of a list to a subclass of list ( tem[:]) 
makes converts the subclass back to its parent... 

The equality of list is rather an ambiguous concept.  For 
instance,  a euclidian vector is usually represented by a list 
of 3 vector components.  So if two vectors are of equal length 
and point in opposite directions, are they equal to each other?

The answer is clearly no.  

The other difficulty is that a list is creted by [], viz. lst = 
[].  So an array has to use the square brackets with great care 
not to be converted back to a list.  

Thanks for your nice example and pointers to docs.
OldAl.
-- 
Algis
http://akabaila.pcug.org.au/StructuralAnalysis.pdf
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-12 Thread Ethan Furman

Chris Angelico wrote:

On Thu, May 12, 2011 at 7:02 AM, Ian  wrote:

In the "real world"  lists of zero items do not exist.
You don't go shopping with a shopping list of zero items.


Actually, yes you do. You maintain your shopping list between trips;
whenever you need something, you put it on the list immediately. Then
when you go shopping, you just take the list with you (if you're
lucky, you don't need to move or copy it at all, you just get another
reference to it). Once you're done, you empty the list - you now have
a shopping list with zero items (until you get home and realize you
forgot something).


Um -- you contradicted Ian, then contradicted yourself -- according to 
your scenario your shopping list is *not* empty when you go to the store 
(otherwise known as "going shopping" ;).


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


os.popen command working differently on Windows

2011-05-12 Thread Ayaskanta Swain
Hi All,

 

Please help me in solving the following issue I am facing while
executing my python script. Basically I am executing the OS specific
move command to move a file/dir from one location to another. I am
executing the 'mv' command on linux & the 'move' DOS command on windows
machine from my python script. Everything works fine on linux & windows
, but the script fails to detect a particular error situation on
Windows, which is very important for my application.

 

Normally the move operation fails if we try to move a directory to a
location where the same directory already exists. That means overwriting
of directories is not allowed by the OS for move operation.

For example on Windows command prompt - "move  /Y  C:\temp\my_dir
C:\stage\profiles\" will fail with Access is Denied message if
C:\stage\profiles\ already contains my_dir inside it. It is an expected
OS behavior. But the problem is that, this error message is not thrown
if the command is executed from a python script.

---

filemove.py script has the following code -

..

import os

 

src = sys.argv[1]

dst = sys.argv[2]

 

# Using the DOS command 'move'. Adding quotes("") to avoid issues with
spaces in the path.

command = 'move' + ' ' + '/Y' + ' ' + '"' + src + '"' + ' ' + '"' + dst
+ '"'

 

try:

os.popen(command)

except IOError:

print 'fatal: failed to execute move command'

except OSError, err:

print >> sys.stderr, "System Error while making a copy from " + src
+ " to " + dst




The script executes without giving any error msg and returns 0 exit
code, but in the back ground the directory is not moved to the
destination. I am providing the source & destination values as command
line arguments to the script.

 

On Linux this type of use case gives me the OS error message "cannot
overwrite directory" which makes it easy for me to catch the error
message & return it the end user. But I wonder why is this not the case
on Windows. Any help to solve this will be great.

 

Thanks

Ayaskant-

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


Re: checking if a list is empty

2011-05-12 Thread Chris Angelico
On Fri, May 13, 2011 at 12:02 AM, Ethan Furman  wrote:
> Chris Angelico wrote:
>>
>> On Thu, May 12, 2011 at 7:02 AM, Ian  wrote:
>>>
>>> In the "real world"  lists of zero items do not exist.
>>> You don't go shopping with a shopping list of zero items.
>>
>> Actually, yes you do. You maintain your shopping list between trips;
>> whenever you need something, you put it on the list immediately. Then
>> when you go shopping, you just take the list with you (if you're
>> lucky, you don't need to move or copy it at all, you just get another
>> reference to it). Once you're done, you empty the list - you now have
>> a shopping list with zero items (until you get home and realize you
>> forgot something).
>
> Um -- you contradicted Ian, then contradicted yourself -- according to your
> scenario your shopping list is *not* empty when you go to the store
> (otherwise known as "going shopping" ;).

Ehh, mea culpa (I shouldn't post in haste). Replace "Actually, yes you
do" with "Actually, yes they do". Indeed you do not *go shopping* with
a list of zero items; but a shopping list with no items on it DOES
exist (when you come back).

def do_shopping():
  if shopping_list:
goto shop; # Muahahahahaha.
for item in shopping_list:
  inventory.append(item)
return; # Muahahahaha again!

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


Re: generate properties code in class dynamically

2011-05-12 Thread nn
On May 12, 9:11 am, JamesEM  wrote:
> Hello,
> I have a python class that contains a dictionary.
> I would like to use python properties to access the elements of the
> dictionary.
> This could be achieved as follows:
>
> class MyClass(object):
>
>     def __init__(self):
>         self.d = {}
>         d['field1'] = 1.0
>         d['field2'] = 'A'
>         d['field3'] = [10.0,20.0,30.0]
>
>     @property
>     def field1(self):
>         return self.d['field1']
>
>     @field1.setter
>     def field1(self, value):
>         self.d['field1'] = value
>
>     @field1.deleter
>     def field1(self):
>         del self.d['field1']
>
>     @property
>     def field2(self):
>         return self.d['field2']
>
>     @field1.setter
>     def field2(self, value):
>         self.d['field2'] = value
>
>     @field1.deleter
>     def field2(self):
>         del self.d['field2']
>
>     @property
>     def field3(self):
>         return self.d['field3']
>
>     @field3.setter
>     def field3(self, value):
>         self.d['field3'] = value
>
>     @field3.deleter
>     def field3(self):
>         del self.d['field3']
>
> However, I am effectively writing the same properties code three
> times.
> I would prefer to generate the properties code dynamically from the
> keys of the dictionaries.
> What I am looking for is something like:
>
> class MyClass(object):
>
>     def __init__(self):
>         self.d = {}
>         d['field1'] = 1.0
>         d['field2'] = 'A'
>         d['field3'] = [10.0,20.0,30.0]
>         for f in d:
>            create_property(f)
>
> where create_property(f) dynamically creates the property code for
> field f in MyClass.
>
> Is this possible?
> If so, how could I do it?
>
> Thanks,
> James

Some searching in the cookbook should help. I found this:

http://code.activestate.com/recipes/577590-dictionary-whos-keys-act-like-attributes-as-well/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.popen command working differently on Windows

2011-05-12 Thread Tim Golden

On 12/05/2011 15:11, Ayaskanta Swain wrote:

Please help me in solving the following issue I am facing while
executing my python script. Basically I am executing the OS specific
move command to move a file/dir from one location to another.


Why? Why not use os.rename or shutil.move which already do
whatever is needed under the covers for different Operating Systems?

os.popen returns a file-like object from which you can read any
error messages generated. You're not doing that, and os.popen
won't raise an error itself unless you, say, pass it a number
rather than a string.


import os

output = os.popen ("dir")
print output.read ()

#
# But note:
#
os.popen ("Nonsen*se")

# raises no exception



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


Re: os.popen command working differently on Windows

2011-05-12 Thread MRAB

On 12/05/2011 15:11, Ayaskanta Swain wrote:

Hi All,

Please help me in solving the following issue I am facing while
executing my python script. Basically I am executing the OS specific
move command to move a file/dir from one location to another. I am
executing the ‘mv’ command on linux & the ‘move’ DOS command on windows
machine from my python script. Everything works fine on linux & windows
, but the script fails to detect a particular error situation on
Windows, which is very important for my application.

Normally the move operation fails if we try to move a directory to a
location where the same directory already exists. That means overwriting
of directories is not allowed by the OS for move operation.

For example on Windows command prompt – *“move /Y C:\temp\my_dir
C:\stage\profiles\”* will fail with *Access is Denied* message if
C:\stage\profiles\ already contains my_dir inside it. It is an expected
OS behavior. But the problem is that, this error message is not thrown
if the command is executed from a python script.

---

filemove.py script has the following code –

..

import os

src = sys.argv[1]
dst = sys.argv[2]

# Using the DOS command 'move'. Adding quotes("") to avoid issues with spaces 
in the path.

command = 'move' + ' ' + '/Y' + ' ' + '"' + src + '"' + ' ' + '"' + dst + '"'

try:
os.popen(command)
except IOError:
print 'fatal: failed to execute move command'
except OSError, err:
print >> sys.stderr, "System Error while making a copy from " + src + " to 
" + dst

……..

The script executes without giving any error msg and returns 0 exit
code, but in the back ground the directory is not moved to the
destination. I am providing the source & destination values as command
line arguments to the script.

On Linux this type of use case gives me the OS error message “cannot
overwrite directory” which makes it easy for me to catch the error
message & return it the end user. But I wonder why is this not the case
on Windows. Any help to solve this will be great.


os.popen(command) will just call the command. If the command fails, its
exit code will be non-zero, but that won't make Python raise an
exception.

os.popen(...) will return an object and you can get the exit code of
the command on closing it:

p = os.popen(command)
exit_code = p.close()

On my PC (Windows XP) I get None (not 0) if the command succeeded and 1
if it failed.
--
http://mail.python.org/mailman/listinfo/python-list


urllib2.urlopen+BadStatusLine+https

2011-05-12 Thread up2date.cyborg

Hi,
I am new to this list, I don't really know if I should post here my request.
Anyway.

The following code is raising httplib.BadStatusLine on urllib2.urlopen(url)

url = 
'https://stat.netaffiliation.com/requete.php?login=xxx&mdp=yyy&debut=2011-05-01&fin=2011-05-12'

response = urllib2.urlopen(url)
content = response.read()
response.close()

if the url is http, it doesn't fail, if it's https://www.gmail.com, it 
doesn't fail neither!

someone could help me to make it work.
When going to the url using a browser, there is no error.
The only thing is that the certificate is signed for another domain.

of course, on my real test I replace xxx and yyy, but anyway the error 
is the same with or without the parameters, even 
https://stat.netaffiliation.com raises the exception...


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


Python 2.7 Debian 6.0. Squeeze

2011-05-12 Thread Jorge Romero
Hi all,

My machine is running Debian Squeeze so my default Python runtime is 2.6.6.

According to Python docs *optparse* library is deprecated and the
development will be moved to *argparse*, which is new in Python 2.7.1. So
now that I'm about to write a script that parse command line arguments
thought would be a good idea to do the transition right now, besides the
good comments about this version.

I tried Googling about Python 2.7 on Debian Squeeze, but did not find
anything but discussions -.-. Anyone out there that can point me some
helpful material or anyone who had luck running 2.7 on Debian?

Thanks in advanced.

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


Re: list equal to subclass of list?

2011-05-12 Thread Eric Snow
On Thu, May 12, 2011 at 6:23 AM, Roy Smith  wrote:

> I have a vague feeling this may have been discussed a long time ago, but
> I can't find the thread, so I'll bring it up again.
>
> I recently observed in the "checking if a list is empty" thread that a
> list and a subclass of list can compare equal:
>
> 
> class MyList(list):
>"I'm a subclass"
>
> l1 = []
> l2 = MyList()
>
> print type(l1), type(l2)
> print type(l1) == type(l2)
> print l1 == l2
> 
>
> when run, prints:
>
>  
> False
> True
>
> The docs say:
>
> [http://docs.python.org/library/stdtypes.html]
> Objects of different types, except different numeric types and different
> string types, never compare equal
>
> [http://docs.python.org/release/2.7/reference/expressions.html#notin]
> objects of different types (emphasis)always compare unequal
>
>
That definitely makes it unclear.  A little further down it says that you
can customize comparison with the __cmp__ special method.  You can also
override implement other specific comparison special methods, like __eq__ in
your classes.  So I can definitely see what you mean.

In the case of list, a list object has a __eq__ method that it uses for
determining equality, rather than using the __eq__ method of the base object
type (which behaves as described in your citation).  Many of the builtin
types have custom special methods for a variety of operators, including
comparison.

Looking over the documentation, it seems like it could be touched up to
alleviate any confusion.  Perhaps rewording to make it clear that the
described behavior is the default for objects, rather than always the case.

-eric


> In the test code above, l1 an l2 are different types, at least in the
> sense that type() returns something different for each of them.  What's
> the intended behavior here?  Either the code is wrong or the docs are
> wrong.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can't get urllib2 or httplib to work with tor & privoxy

2011-05-12 Thread Bob Fnord
Chris Angelico  wrote:

> On Tue, May 10, 2011 at 4:20 AM, Bob Fnord  wrote:
> > Both methods give me a 503 error...
> 
> As a networking geek, my first thought would be to fire up a tiny
> little "snoop server" and see what, exactly, the two methods are
> doing. (Ignore the HTTPS options as they're more complicated to snoop
> on; you're almost certainly going to see exactly the same on the
> HTTP.)
> 
> A snoop server is simply an HTTP server that dumps its requests to
> stdout or a file, utterly raw. You can write one in Python fairly
> easily, or use another program; if I'm working on Windows, I'll
> generally use my own RosMud MUD client, but you'll be able to whip up
> a cross-platform one in half a page of code in any decent high level
> language. I recommend you work at the sockets level, rather than using
> an HTTP library, unless you have one that can emit the entire request,
> exactly as it came from the client.
> 
> Once you've found the difference(s) between Lynx and your script, you
> can see what's causing the 503 (Service Unavailable) error; it may be
> that you need to authenticate with the proxy.

Duh, I was doing something else stupid. 
Thanks but never mind!

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


Re: Python 2.7 Debian 6.0. Squeeze

2011-05-12 Thread Jorge Romero
Actually came back with some feedback to my own question.

The following repositories do the job:

# /etc/apt/sources.list
deb http://ftp.uk.debian.org/debian/ unstable main contrib non-free
deb http://ftp.uk.debian.org/debian/ experimental main contrib non-free
deb http://security.debian.org/ testing/updates main contrib

$ apt-get update
$ apt-get install python2.7
$ python --version
Python 2.6.6
$ python2.7 --version
Python 2.7.1+

If you need 2.7 as default runtime:

$ update-alternatives --install /usr/bin/python python /usr/bin/python2.7 10

This is the first time I need two Python instances, so might helpful for
someone in the same position. Any further help feel free to reply.

Cheers.

On Thu, May 12, 2011 at 11:27 AM, Jorge Romero wrote:

> Hi all,
>
> My machine is running Debian Squeeze so my default Python runtime is 2.6.6.
>
> According to Python docs *optparse* library is deprecated and the
> development will be moved to *argparse*, which is new in Python 2.7.1. So
> now that I'm about to write a script that parse command line arguments
> thought would be a good idea to do the transition right now, besides the
> good comments about this version.
>
> I tried Googling about Python 2.7 on Debian Squeeze, but did not find
> anything but discussions -.-. Anyone out there that can point me some
> helpful material or anyone who had luck running 2.7 on Debian?
>
> Thanks in advanced.
>
> --
> Jorge Romero
>
>


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


Python enabled gdb on Windows and relocation

2011-05-12 Thread Ruben Van Boxem
Hi,

I am currently trying to integrate Python support into my toolchain build
(including GDB of course). It is a sysrooted binutils+GCC+GDB+mingw-w64
toolchain.

I currently have the basic setup working: I can link gdb with my manually
generated import lib to the python dll from the official Windows install. If
there is anything I am missing or a very easy solution to the problems
decsribed below, please just say so. I am only suggesting what I would like
to happen.

Now on to the problems I'd like to discuss:

1. gdb.exe won't start without me having set PYTHONPATH manually. I
understand the need for this, but as gdb requires Python 2, and users of my
toolchain may have installed Python 3 or a 32-bit version python they want
to use from the same environment (without changing their own PYTHONPATH),
there is no way to run python-enabled gdb. What I suggest is perhaps a
Windows only change: a kind of "sysroot"ed gdb+python, so that the python
used by gdb is truly built in. I cannot require everyone using my toolchain
to install the correct python version for obvious reasons (Windows != Linux
in this regard). However way this is tackled, the gdb I want should look
relative to it's current (relocatable) directory for Python modules/*;py
files in a well-defined directory at build time. That would allow me to
distribute gdb in a very clear way:


/bin
/bin/python27.dll
/bin/gdb.exe
/lib
/lib/python27
/lib/python27/

Currently, this scheme only works if I manually set the PYTHONPATH
environment variable to /lib/python27. This global environment
variable could conflict with existing Python installations, that may have
another bitness (I have 64- and 32-bit toolchains). I think you can see
there are problems enough with the current set up. I also read this old
discussion: http://comments.gmane.org/gmane.comp.gdb.patches/62811 that
might imply that the PYTHONPATH check is something built-in to the python
dll. Can anyone shed some light on this?

2. With PYTHONPATH set as a temporary workaround, gdb starts, but spits out
a traceback:
Traceback (most recent call last):
  File "", line 35, in 
  File "m:\development\mingw64\share\gdb/python/gdb/__init__.py", line 18,
in 
gdb.command.pretty_printers.register_pretty_printer_commands()
  File
"m:\development\mingw64\share\gdb/python/gdb\command\pretty_printers.py",
line 368, in register_pretty_printer_commands
InfoPrettyPrinter()
  File
"m:\development\mingw64\share\gdb/python/gdb\command\pretty_printers.py",
line 100, in __init__
gdb.COMMAND_DATA)
RuntimeError: Could not find command prefix info.

This is a minor problem I think, as "python import time" "python print
time.clock()" works as expected. What is wrong?

Thanks very much!

Ruben

PS: I've sent this to both the gdb and python mailing lists, as these issues
have a large overlap to both projects.
PS2: Please reply-to-all as I do not want daily mails from both mailing
lists on every issue brought up there. My apologies.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode by default

2011-05-12 Thread Ian Kelly
On Thu, May 12, 2011 at 1:58 AM, John Machin  wrote:
> On Thu, May 12, 2011 4:31 pm, harrismh777 wrote:
>
>>
>> So, the UTF-16 UTF-32 is INTERNAL only, for Python
>
> NO. See one of my previous messages. UTF-16 and UTF-32, like UTF-8 are
> encodings for the EXTERNAL representation of Unicode characters in byte
> streams.

Right.  *Under the hood* Python uses UCS-2 (which is not exactly the
same thing as UTF-16, by the way) to represent Unicode strings.
However, this is entirely transparent.  To the Python programmer, a
unicode string is just an abstraction of a sequence of code-points.
You don't need to think about UCS-2 at all.  The only times you need
to worry about encodings are when you're encoding unicode characters
to byte strings, or decoding bytes to unicode characters, or opening a
stream in text mode; and in those cases the only encoding that matters
is the external one.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python enabled gdb on Windows and relocation

2011-05-12 Thread Ruben Van Boxem
(now in plain-text as required by gdb mailing list)

Hi,

I am currently trying to integrate Python support into my toolchain
build (including GDB of course). It is a sysrooted
binutils+GCC+GDB+mingw-w64 toolchain.

I currently have the basic setup working: I can link gdb with my
manually generated import lib to the python dll from the official
Windows install. If there is anything I am missing or a very easy
solution to the problems decsribed below, please just say so. I am
only suggesting what I would like to happen.

Now on to the problems I'd like to discuss:

1. gdb.exe won't start without me having set PYTHONPATH manually. I
understand the need for this, but as gdb requires Python 2, and users
of my toolchain may have installed Python 3 or a 32-bit version python
they want to use from the same environment (without changing their own
PYTHONPATH), there is no way to run python-enabled gdb. What I suggest
is perhaps a Windows only change: a kind of "sysroot"ed gdb+python, so
that the python used by gdb is truly built in. I cannot require
everyone using my toolchain to install the correct python version for
obvious reasons (Windows != Linux in this regard). However way this is
tackled, the gdb I want should look relative to it's current
(relocatable) directory for Python modules/*;py files in a
well-defined directory at build time. That would allow me to
distribute gdb in a very clear way:


/bin
/bin/python27.dll
/bin/gdb.exe
/lib
/lib/python27
/lib/python27/

Currently, this scheme only works if I manually set the PYTHONPATH
environment variable to /lib/python27. This global environment
variable could conflict with existing Python installations, that may
have another bitness (I have 64- and 32-bit toolchains). I think you
can see there are problems enough with the current set up. I also read
this old discussion:
http://comments.gmane.org/gmane.comp.gdb.patches/62811 that might
imply that the PYTHONPATH check is something built-in to the python
dll. Can anyone shed some light on this?

2. With PYTHONPATH set as a temporary workaround, gdb starts, but
spits out a traceback:
Traceback (most recent call last):
  File "", line 35, in 
  File "m:\development\mingw64\share\gdb/python/gdb/__init__.py", line
18, in 
    gdb.command.pretty_printers.register_pretty_printer_commands()
  File "m:\development\mingw64\share\gdb/python/gdb\command\pretty_printers.py",
line 368, in register_pretty_printer_commands
    InfoPrettyPrinter()
  File "m:\development\mingw64\share\gdb/python/gdb\command\pretty_printers.py",
line 100, in __init__
    gdb.COMMAND_DATA)
RuntimeError: Could not find command prefix info.

This is a minor problem I think, as "python import time" "python print
time.clock()" works as expected. What is wrong?

Thanks very much!

Ruben

PS: I've sent this to both the gdb and python mailing lists, as these
issues have a large overlap to both projects.
PS2: Please reply-to-all as I do not want daily mails from both
mailing lists on every issue brought up there. My apologies.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list equal to subclass of list?

2011-05-12 Thread Roy Smith
On May 12, 2011, at 11:30 AM, Eric Snow wrote:

> On Thu, May 12, 2011 at 6:23 AM, Roy Smith  wrote:
> The docs say:
> 
> [http://docs.python.org/library/stdtypes.html]
> Objects of different types, except different numeric types and different
> string types, never compare equal
> 
> [http://docs.python.org/release/2.7/reference/expressions.html#notin]
> objects of different types (emphasis)always compare unequal
> 
> 
> That definitely makes it unclear.

I don't think it's unclear at all.  It's very clear.  Clearly wrong :-)

> A little further down it says that you can customize comparison with the 
> __cmp__ special method.

Yes, and that says:

The operators <, >, ==, >=, <=, and != compare the values of two objects. The 
objects need not have the same type. If both are numbers, they are converted to 
a common type. Otherwise, objects of different types always compare unequal, 
and are ordered consistently but arbitrarily. You can control comparison 
behavior of objects of non-built-in types by defining a __cmp__ method or rich 
comparison methods like __gt__, described in section Special method names.

I read that as saying that if you implement __eq__(), you must make sure that 
it returns False if self and other have different types (and likewise, __ne__() 
should return True for that case).  The same way that it says that 
obj1.__lt__(obj2) must return a consistent result for all types of obj1 and 
obj2.

> Looking over the documentation, it seems like it could be touched up to 
> alleviate any confusion.  Perhaps rewording to make it clear that the 
> described behavior is the default for objects, rather than always the case.

That would be a start, but doesn't address this specific problem.  If the docs 
are changed to say that "type(obj1) != type(obj2) implies obj1 != obj2" in only 
the default, people will assume that list follows this default rule since it's 
a built-in type.  Built-in types which don't follow the default rule need to 
have their behavior documented.

---
Roy Smith
[email protected]





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


Re: list equal to subclass of list?

2011-05-12 Thread Ethan Furman

Roy Smith wrote:
I recently observed in the "checking if a list is empty" thread that a 
list and a subclass of list can compare equal:



class MyList(list):
"I'm a subclass"

l1 = []
l2 = MyList()

print type(l1), type(l2)
print type(l1) == type(l2)
print l1 == l2


when run, prints:

 
False
True

The docs say:

[http://docs.python.org/library/stdtypes.html]
Objects of different types, except different numeric types and different 
string types, never compare equal


This part of the documentation is talking about built-in types, which 
your MyList is not.




[http://docs.python.org/release/2.7/reference/expressions.html#notin]
objects of different types *always* compare unequal


Should probably have the word 'built-in' precede 'types' here, since 
constructed objects can do whatever they have been told to do.


In the test code above, l1 an l2 are different types, at least in the 
sense that type() returns something different for each of them.


--> MyList.__mro__
(, , )

MyList is a list -- just a more specific kind of list -- as can be seen 
from its mro; this is analogous to a square (2 sets of parallel lines 
joined at 90 degree angles, both sets being the same length) also being 
a rectangle (2 sets of parallel lines joined at 90 degree angles).



What's the intended behavior here?  Either the code is wrong or the docs

> are wrong.

The code is correct.

~Ethan~

PS
Yes, I know my square/rectangle definitions are incomplete, thanks.  ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Slice implementation bug

2011-05-12 Thread Robert Kern

On 5/12/11 6:06 AM, Tambet wrote:

Hello!

Let's say slice is multidimensional now - how to interpret it?

I excpect these to work:

* m[0, 3] - get one element from matrix
* m[0:2, 0:2] - get four elements from matrix, iterate over them (I have
  actually an rtree if it doesn't make sense to you)

But it won't, because if m[0, 3] returns something, then m[0:2, 0:2] cannot
yield anymore.


Let me try to rephrase, since you seem to be leaving out a lot of assumptions. 
You are trying to say that you want m[0:2,0:2] to return an iterator and that if 
you define __getitem__() such that m[0,3] returns a value, then you cannot 
implement __getitem__() to be a generator using a yield statement.


Okay. Fine.

But there is no reason that __getitem__() needs to be a generator function for 
you to return an iterator. You can simply return another generator. For example:


def __getitem__(self, key):
if isinstance(key, tuple):
if any(isinstance(x, slice) for x in key):
return self._generate_from_slice(key)
# The default, boring case.
return self._get_value(key)

def _generate_from_slice(self, key):
yield foo
yield bar
yield etc


Ofcourse I could return an iterator, but this would not be so simple.


Really, it is.

--
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: checking if a list is empty

2011-05-12 Thread [email protected]
On 05/12/2011 12:13 AM, Steven D'Aprano wrote:
>[snip]
> http://www.codinghorror.com/blog/2006/07/separating-programming-sheep-from-non-programming-goats.html
>
> Shorter version: it seems that programming aptitude is a bimodal
> distribution, with very little migration from the "can't program" hump
> into the "can program" hump. There does seem to be a simple predictor for
> which hump you fall into: those who intuitively develop a consistent
> model of assignment (right or wrong, it doesn't matter, so long as it is
> consistent) can learn to program. Those who don't, can't.

A later paper by the same authors...
(http://www.eis.mdx.ac.uk/research/PhDArea/saeed/paper3.pdf)

Abstract:
[...] Despite a great deal of research into teaching methods
and student responses, there have been to date no strong
predictors of success in learning to program.  Two years ago
we appeared to have discovered an exciting and enigmatic new
predictor of success in a first programming course. We now
report that after six experiments, involving more than 500
students at six institutions in three countries, the predictive
effect of our test has failed to live up to that early promise.
We discuss the strength of the effects that have been observed
and the reasons for some apparent failures of prediction.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list equal to subclass of list?

2011-05-12 Thread Ethan Furman

Roy Smith wrote:

On May 12, 2011, at 11:30 AM, Eric Snow wrote:


That definitely makes it unclear.


I don't think it's unclear at all.  It's very clear.  Clearly wrong :-)


While it is wrong (it should have 'built-in' precede the word 'types'), 
it is not wrong in the way you think -- a subclass *is* a type of its 
superclass.



A little further down it says that you can customize comparison with 
the __cmp__ special method. 

>
I read that as saying that if you implement __eq__(), you must make sure 
that it returns False if self and other have different types (and 
likewise, __ne__() should return True for that case).


Your understanding is flawed.  If your object does not know how to 
compare itself to some other object, it should return NotImplemented -- 
at that point Python will follow the rules outlined in the docs.  By 
returning NotImplemented you are allowing the other object a chance to 
perform the comparison -- after all, it might know how!  :)  If the 
other object also returns NotImplemented then (drum-roll please) they 
won't compare equal.




The same way that it says that obj1.__lt__(obj2) must return a consistent

> result for all types of obj1 and obj2.

Where do you see that?  I couldn't find it.

The point of being able to write your own rich comparison methods is so 
you can control what happens -- there is no "must" about it.  This is 
Python -- do what you want!  :)


~Ethan~

PS
I have a broken sense of humor -- sometimes it works, sometimes it 
doesn't.  My apologies in advance if my attempt at humor was not funny.

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


Re: Proper way to handle errors in a module

2011-05-12 Thread Andrew Berg
On 2011.05.11 01:05 PM, Roy Smith wrote:
> You want to raise specific errors.  Let's say you've got a function like 
> this:
>
> def airspeed(swallow):
>speeds = {"european": 42,
>  "african", 196}
>return speeds[swallow]
>
> If somebody passes an invalid string, it will raise KeyError as written.  
> Better to do something like:
>
> def airspeed(swallow):
>speeds = {"european": 42,
>  "african", 196}
>try:
>return speeds[swallow]
>except KeyError:
> raise UnknownBirdError(swallow)
Is there any way to do this without purposely setting up the code to
trigger an arbitrary exception if the function can't do its job? That
is, can I raise an UnknownBirdError outside of an except clause, and if
so, how? I can't find much help for doing this in Python 3, even in the
official docs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Hi all. I need aid in creating script to blender.

2011-05-12 Thread Jean Carlos Páez Ramírez

Hello. 



The attached file is script of blender fact in python that .tmb serves to
concern archives (secondly attached file), unloadings to blender and uses
script and concerns the second file that you shipment you see so that it.
Everything can be published and, but it is not possible to be exported again to
.tmb 



To unload in this Link: http://www.blender.org/

script: http://www.mediafire.com/?clmdgkymsfooddd

secondly attached file: http://www.mediafire.com/?lbmj594ru6r4b67



PD: I need script to export in extension .tmb



Thanks.


Buen día comunidad 



Hola.



El archivo adjunto es un script de blender hecho en python que sirve para
importar archivos .tmb (http://www.mediafire.com/?clmdgkymsfooddd), descargas 
blender y usa el
script e importa el segundo archivo que te envio para que lo veas 
(http://www.mediafire.com/?lbmj594ru6r4b67). El se puede
editar y todo, pero no se puede exportar de nuevo a .tmb







link del
script: http://www.mediafire.com/?clmdgkymsfooddd

Segundo archivo adjunto: http://www.mediafire.com/?lbmj594ru6r4b67



PD: Necesito el script para exportar en extension .tmb En si necesito ayuda en 
ese diseño de un script que exporte de .blend a .tmb







Gracias.














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


Re: Me ayudas? Hi . I need aid in creating script to blender.

2011-05-12 Thread Felipe Vinturini
2011/5/12 Jean Carlos Páez Ramírez 

>  Hello.
>
> The attached file is script of blender fact in python that .tmb serves to
> concern archives (secondly attached file), unloadings to blender and uses
> script and concerns the second file that you shipment you see so that it.
> Everything can be published and, but it is not possible to be exported again
> to .tmb
>
> To unload in this Link: http://www.blender.org/
> script: http://www.mediafire.com/?clmdgkymsfooddd
> secondly attached file: http://www.mediafire.com/?lbmj594ru6r4b67
>
> PD: I need script to export in extension .tmb in BLENDER.
>
> Thanks.
>
> --
> Buen día comunidad
>
> Hola.
>
> El archivo adjunto es un script de blender hecho en python que sirve para
> importar archivos .tmb (http://www.mediafire.com/?clmdgkymsfooddd),
> descargas blender y usa el script e importa el segundo archivo que te envio
> para que lo veas (http://www.mediafire.com/?lbmj594ru6r4b67). El se puede
> editar y todo, pero no se puede exportar de nuevo a .tmb
>
>
> link del script: http://www.mediafire.com/?clmdgkymsfooddd
> Segundo archivo adjunto: http://www.mediafire.com/?lbmj594ru6r4b67
>
> PD: Necesito el script para exportar en extension .tmb En si necesito ayuda
> en ese diseño de un script que exporte de .blend a .tmb
>
>
>
> Gracias.
>

Hei!

If you don't try to do anything, nobody will help you...

That's why you didn't have any answer for all your posts!

I think you got the point...

Sorry.

Regads,
Felipe.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proper way to handle errors in a module

2011-05-12 Thread MRAB

On 12/05/2011 20:14, Andrew Berg wrote:

On 2011.05.11 01:05 PM, Roy Smith wrote:

You want to raise specific errors.  Let's say you've got a function like
this:

def airspeed(swallow):
speeds = {"european": 42,
  "african", 196}
return speeds[swallow]

If somebody passes an invalid string, it will raise KeyError as written.
Better to do something like:

def airspeed(swallow):
speeds = {"european": 42,
  "african", 196}
try:
return speeds[swallow]
except KeyError:
 raise UnknownBirdError(swallow)

Is there any way to do this without purposely setting up the code to
trigger an arbitrary exception if the function can't do its job? That
is, can I raise an UnknownBirdError outside of an except clause, and if
so, how? I can't find much help for doing this in Python 3, even in the
official docs.

>
You can raise an exception wherever you like! :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Me ayudas? Hi . I need aid in creating script to blender.

2011-05-12 Thread Felipe Vinturini
2011/5/12 Jean Carlos Páez Ramírez 

>  To ok there is no problem friend, of all ways thanks, I will see that I
> can do, nor in the pages Web of blender they answer to me.
>
> Thanks friend.
>
> Regads,
>
> Jean P.
>
> --
> From: [email protected]
> Date: Thu, 12 May 2011 16:23:12 -0300
> Subject: Re: Me ayudas? Hi . I need aid in creating script to blender.
> To: [email protected]
> CC: [email protected]
>
>
>
> 2011/5/12 Jean Carlos Páez Ramírez 
>
>  Hello.
>
> The attached file is script of blender fact in python that .tmb serves to
> concern archives (secondly attached file), unloadings to blender and uses
> script and concerns the second file that you shipment you see so that it.
> Everything can be published and, but it is not possible to be exported again
> to .tmb
>
> To unload in this Link: http://www.blender.org/
> script: http://www.mediafire.com/?clmdgkymsfooddd
> secondly attached file: http://www.mediafire.com/?lbmj594ru6r4b67
>
> PD: I need script to export in extension .tmb in BLENDER.
>
> Thanks.
>
> --
> Buen día comunidad
>
> Hola.
>
> El archivo adjunto es un script de blender hecho en python que sirve para
> importar archivos .tmb (http://www.mediafire.com/?clmdgkymsfooddd),
> descargas blender y usa el script e importa el segundo archivo que te envio
> para que lo veas (http://www.mediafire.com/?lbmj594ru6r4b67). El se puede
> editar y todo, pero no se puede exportar de nuevo a .tmb
>
>
> link del script: http://www.mediafire.com/?clmdgkymsfooddd
> Segundo archivo adjunto: http://www.mediafire.com/?lbmj594ru6r4b67
>
> PD: Necesito el script para exportar en extension .tmb En si necesito ayuda
> en ese diseño de un script que exporte de .blend a .tmb
>
>
> Gracias.
>
>
> Hei!
>
> If you don't try to do anything, nobody will help you...
>
> That's why you didn't have any answer for all your posts!
>
> I think you got the point...
>
> Sorry.
>
> Regads,
> Felipe.
>

Ok, no problem! When you have something come back...

Also, don't forget to always copy the list on your posts and try no to top
post...

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


Re: checking if a list is empty

2011-05-12 Thread Terry Reedy

On 5/11/2011 8:26 AM, Roy Smith wrote:


I conclude that li == [] should have returned False.  Either I'm not
understanding things correctly, or this is a bug.


The doc is wrong (and not only on this). I am working on a report with 
suggested fixes. Will post number when finish.


--
Terry Jan Reedy

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


Re: py3k buffered IO - flush() required between read/write?

2011-05-12 Thread Terry Reedy

On 5/12/2011 9:30 AM, Genstein wrote:

With 3.2 on winxp, that is what I get with StringIO, text file, and
bytes file (the first two with b's removed). I would expect the same on
any system. If you get anything different, I would consider it a bug


Thanks Terry, you're entirely right there; I trimmed down my test case,
asked for confirmation and have reported it as
http://bugs.python.org/issue12062. Noted here in case anyone else trips
over it.


I want people to know that with a simple, minimal, easy to run and 
reproduce and think about test case posted, more info, more test cases, 
and probable fixes were posted within an hour. (Fixes are not always 
that quick, but stripping away irrelevancies really helps speed the 
process.)


--
Terry Jan Reedy

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


Re: generate properties code in class dynamically

2011-05-12 Thread Terry Reedy

On 5/12/2011 9:11 AM, JamesEM wrote:


I would prefer to generate the properties code dynamically from the
keys of the dictionaries.
What I am looking for is something like:

class MyClass(object):

 def __init__(self):
 self.d = {}
 d['field1'] = 1.0
 d['field2'] = 'A'
 d['field3'] = [10.0,20.0,30.0]
 for f in d:
create_property(f)

where create_property(f) dynamically creates the property code for
field f in MyClass.

Is this possible?


Without actually trying, I am not sure, but I believe maybe (possibly 
version dependent). The init method is the wrong place. Create the 
properties exactly once, just after the class is created. It is possible 
to add functions to classes as attributes (instance methods) after they 
are created. The property decorators *might* require that they be 
invoked with the class body, I do not know. I would first try with 
property().


Assuming dict name 'd' is fixed:

def gsd(key):
  def get(self):
return self.d[key]
  def set(self, value):
self.d[key] = value
  def del(self):
del self.d[key]
  return get,set,del

for key in fieldnames:
  setattr(MyClass, key, property(*gsd(key)))

For recent versions, this could be done within a class decorator, but 
that is only convenient syntactic sugar.


--
Terry Jan Reedy

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


Re: Proper way to handle errors in a module

2011-05-12 Thread Andrew Berg
On 2011.05.12 02:25 PM, MRAB wrote:
> You can raise an exception wherever you like! :-)
If I raise an exception that isn't a built-in exception, I get something
like "NameError: name 'HelloError' is not defined". I don't know how to
define the exception.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Customize help output from optparse (or argparse)

2011-05-12 Thread Thomas 'PointedEars' Lahn
Thorsten Kampe wrote:

> I'm using optparse for a little Python script.
> 
> 1. The output from "--help" is:
> """
> Usage: script.py 
> 
> script.py does something
> 
> Options:
>   -h, --help   show this help message and exit
> """
> 
> I would prefer to have the description before the usage, like...
> """
> script.py does something
> 
> Usage: script.py 
> 
> Options:
>   -h, --help   show this help message and exit
> """
> 
> 2. The output from "--doesnotexit" is:
> """
> Usage: script.py 
> 
> script.py: error: no such option: --doesnotexist
> """
> 
> I would prefer to have the error first, then the usage and additionally
> the options, like...
> """
> script.py: error: no such option: --doesnotexist
> 
> Usage: script.py 
> 
> Options:
>   -h, --help   show this help message and exit
> """
> 
> Is that possible with either optparse or the "new kid on the block"
> argparse. If so how?

You can easily have #1 with optparse.OptionParser(usage="…")¹, but optparse 
is deprecated in favor of argparse.ArgumentParser.  I do not think you can 
have #2 with either optparse or argparse: OptionParser() would print the 
error message last, and ArgumentParser() would not print the description
on error.  Subclassing ArgumentParser might be feasible, though.

__
¹  
-- 
PointedEars

Bitte keine Kopien per E-Mail. / Please do not Cc: me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proper way to handle errors in a module

2011-05-12 Thread Corey Richardson
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 05/12/2011 04:12 PM, Andrew Berg wrote:
> On 2011.05.12 02:25 PM, MRAB wrote:
>> You can raise an exception wherever you like! :-)
> If I raise an exception that isn't a built-in exception, I get something
> like "NameError: name 'HelloError' is not defined". I don't know how to
> define the exception.

class HelloError(Exception):
pass

Of course, there are all sorts of other things you could do with your
exception.

http://docs.python.org/tutorial/errors.html#user-defined-exceptions
- -- 
Corey Richardson
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.17 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iQEcBAEBAgAGBQJNzED9AAoJEAFAbo/KNFvp1uQIAKFaKyD1Q3RL7LGFSmnyRFTK
9XWRH3CSM9mOALccfQ8bUkrquol1fAqhrm4jyOW0scWmsJpRlcb6Rj4HtrmMQOuG
DpsUzEZCTnT9Xk80OeTFbpWWBIVBkxdhCxCl75XAP22o5EjhHpgLyqoqMD+81BKH
5/JWAGRJx/9E4BvNWsxIUhb1jlz+XT4H1XykTE1UUOP0uZneWRJMs7P12WNiL2Ii
HT0hEUhQc1eP1fJ5BqPB/6/B9q/KxTbN55hCq1VwwfRhgbaM4kR7Bekri7QUHGAK
1MKxRa1v+Co59y+ywAIH92L3wky3xNyFrUlFzK4AwYOnwRkVvUWw7vPG1iShE+k=
=2+y6
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proper way to handle errors in a module

2011-05-12 Thread Tycho Andersen
On Thu, May 12, 2011 at 03:12:39PM -0500, Andrew Berg wrote:
> On 2011.05.12 02:25 PM, MRAB wrote:
> > You can raise an exception wherever you like! :-)
> If I raise an exception that isn't a built-in exception, I get something
> like "NameError: name 'HelloError' is not defined". I don't know how to
> define the exception.

You'll have to define it, as you would anything else (exceptions are
just regular "things"; in fact you can raise anything that's a class
or instance). I typically don't put a whole lot in my exception
classes, though.

point:~/working$ python
Python 2.6.2 (r262:71600, Jun  8 2009, 11:11:42) 
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class HelloError(Exception): pass
... 
>>> raise HelloError("hello!")
Traceback (most recent call last):
  File "", line 1, in 
  __main__.HelloError: hello!

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


Re: Proper way to handle errors in a module

2011-05-12 Thread MRAB

On 12/05/2011 21:12, Andrew Berg wrote:

On 2011.05.12 02:25 PM, MRAB wrote:

You can raise an exception wherever you like! :-)

If I raise an exception that isn't a built-in exception, I get something
like "NameError: name 'HelloError' is not defined". I don't know how to
define the exception.


Define it as a subclass of Exception:

class UnknownBirdError(Exception):
pass
--
http://mail.python.org/mailman/listinfo/python-list


Re: Proper way to handle errors in a module

2011-05-12 Thread Ethan Furman

Andrew Berg wrote:

On 2011.05.12 02:25 PM, MRAB wrote:

You can raise an exception wherever you like! :-)

If I raise an exception that isn't a built-in exception, I get something
like "NameError: name 'HelloError' is not defined". I don't know how to
define the exception.


class HelloError(Exception):
"custom exception"

and that's all you need.  You can override __init__ to add your own 
attributes, etc, if you need to.


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


Re: Proper way to handle errors in a module

2011-05-12 Thread Andrew Berg
On 2011.05.12 03:20 PM, Corey Richardson wrote:
> class HelloError(Exception):
> pass
>
> Of course, there are all sorts of other things you could do with your
> exception.
>
> http://docs.python.org/tutorial/errors.html#user-defined-exceptions
So that's where that info is. I wasn't looking in the tutorial section.
Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py3k buffered IO - flush() required between read/write?

2011-05-12 Thread Genstein

On 12/05/2011 20:44, Terry Reedy wrote:

I want people to know that with a simple, minimal, easy to run and
reproduce and think about test case posted, more info, more test cases,
and probable fixes were posted within an hour. (Fixes are not always
that quick, but stripping away irrelevancies really helps speed the
process.)


A very good point. I'm extremely impressed with the speed and deftness 
which the bug was handled once raised. Hats off to the people involved.


I should have posted a short test case initially, but I knew it would 
take some time for me to produce and didn't want to go that far if it 
was clear to everyone but me that flushes were required by design :)


Thanks again,
-eg.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Customize help output from optparse (or argparse)

2011-05-12 Thread Karim

On 05/12/2011 10:22 PM, Thomas 'PointedEars' Lahn wrote:

Thorsten Kampe wrote:


I'm using optparse for a little Python script.

1. The output from "--help" is:
"""
Usage: script.py

script.py does something

Options:
   -h, --help   show this help message and exit
"""

I would prefer to have the description before the usage, like...
"""
script.py does something

Usage: script.py

Options:
   -h, --help   show this help message and exit
"""

2. The output from "--doesnotexit" is:
"""
Usage: script.py

script.py: error: no such option: --doesnotexist
"""

I would prefer to have the error first, then the usage and additionally
the options, like...
"""
script.py: error: no such option: --doesnotexist

Usage: script.py

Options:
   -h, --help   show this help message and exit
"""

Is that possible with either optparse or the "new kid on the block"
argparse. If so how?

You can easily have #1 with optparse.OptionParser(usage="…")¹, but optparse
is deprecated in favor of argparse.ArgumentParser.  I do not think you can
have #2 with either optparse or argparse: OptionParser() would print the
error message last, and ArgumentParser() would not print the description
on error.  Subclassing ArgumentParser might be feasible, though.

__
¹


Please find documentation to configure help in ArgumentParser BUT for 
argparse module:


- HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
  50 ArgumentDefaultsHelpFormatter -- Formatter classes which
  51 may be passed as the formatter_class= argument to the
  52 ArgumentParser constructor. HelpFormatter is the default,
  53 RawDescriptionHelpFormatter and RawTextHelpFormatter tell 
the parser

  54 not to change the formatting for help text, and
  55 ArgumentDefaultsHelpFormatter adds information about 
argument defaults

  56 to the help.

So It seems easy to a different pass formatter_class to ArgumentParser. 
You can inherite

from HelpFormater class but you have to know the implementation details:
File is located at /lib/python2.7/argparse.py

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


Re: unicode by default

2011-05-12 Thread Terry Reedy

On 5/12/2011 12:17 PM, Ian Kelly wrote:

On Thu, May 12, 2011 at 1:58 AM, John Machin  wrote:

On Thu, May 12, 2011 4:31 pm, harrismh777 wrote:



So, the UTF-16 UTF-32 is INTERNAL only, for Python


NO. See one of my previous messages. UTF-16 and UTF-32, like UTF-8 are
encodings for the EXTERNAL representation of Unicode characters in byte
streams.


Right.  *Under the hood* Python uses UCS-2 (which is not exactly the
same thing as UTF-16, by the way) to represent Unicode strings.


I know some people say that, but according to the definitions of the 
unicode consortium, that is wrong! The earlier UCS-2 *cannot* represent 
chars in the Supplementary Planes. The later (1996) UTF-16, which Python 
uses, can. The standard considers 'UCS-2' obsolete long ago. See


https://secure.wikimedia.org/wikipedia/en/wiki/UTF-16/UCS-2
or http://www.unicode.org/faq/basic_q.html#14

The latter says: "Q: What is the difference between UCS-2 and UTF-16?
A: UCS-2 is obsolete terminology which refers to a Unicode 
implementation up to Unicode 1.1, before surrogate code points and 
UTF-16 were added to Version 2.0 of the standard. This term should now 
be avoided."


It goes on: "Sometimes in the past an implementation has been labeled 
"UCS-2" to indicate that it does not support supplementary characters 
and doesn't interpret pairs of surrogate code points as characters. Such 
an implementation would not handle processing of character properties, 
code point boundaries, collation, etc. for supplementary characters."


I know that 16-bit Python *does* use surrogate pairs for supplementary 
chars and at least some properties work for them. I am not sure exactly 
what the rest means.



However, this is entirely transparent.  To the Python programmer, a
unicode string is just an abstraction of a sequence of code-points.
You don't need to think about UCS-2 at all.  The only times you need
to worry about encodings are when you're encoding unicode characters
to byte strings, or decoding bytes to unicode characters, or opening a
stream in text mode; and in those cases the only encoding that matters
is the external one.


If one uses unicode chars in the Supplementary Planes above the BMP (the 
first 2**16), which require surrogate pairs for 16 bit unicode (UTF-16), 
then the abstraction leaks.


--
Terry Jan Reedy

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


Re: list equal to subclass of list?

2011-05-12 Thread Thomas 'PointedEars' Lahn
Ethan Furman wrote:

> PS
> I have a broken sense of humor -- sometimes it works, sometimes it
> doesn't.  My apologies in advance if my attempt at humor was not funny.

Now that was very unpythonic.  Know where your roots are! :)

-- 
PointedEars

Bitte keine Kopien per E-Mail. / Please do not Cc: me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need Assistance on this program.

2011-05-12 Thread Thomas 'PointedEars' Lahn
vijay swaminathan wrote:

> I have already done that. But for some reason my response went
> as a new thread. Attaching the code again.

JFYI: Please DO NOT post attachments in a non-binary newsgroup
or to a mailing list (are there binary ones at all?) again.  TIA.

-- 
PointedEars

Bitte keine Kopien per E-Mail. / Please do not Cc: me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list equal to subclass of list?

2011-05-12 Thread Roy Smith
On May 12, 2:29 pm, Ethan Furman  wrote:

> While it is wrong (it should have 'built-in' precede the word 'types'),
> it is not wrong in the way you think -- a subclass *is* a type of its
> superclass.

Well, consider this:

class List_A(list):
"A list subclass"

class List_B(list):
"Another list subclass"

a = List_A()
b = List_B()
print a == b

It prints "True".  Neither a nor b are a type of the other:

print isinstance(List_A, List_B)
print isinstance(List_B, List_A)

False
False

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


Re: list equal to subclass of list?

2011-05-12 Thread Ethan Furman

Roy Smith wrote:

On May 12, 2:29 pm, Ethan Furman  wrote:


While it is wrong (it should have 'built-in' precede the word 'types'),
it is not wrong in the way you think -- a subclass *is* a type of its
superclass.


Well, consider this:

class List_A(list):
"A list subclass"

class List_B(list):
"Another list subclass"

a = List_A()
b = List_B()
print a == b

It prints "True".  Neither a nor b are a type of the other:

print isinstance(List_A, List_B)
print isinstance(List_B, List_A)

False
False


Okay, considering:
List_A is a user-defined type.
List_B is a user-defined type.
Both are sub-classes of list.
Corrected documentation (which says 'built-in types' etc, etc) says 
nothing about user-defined types not being able to be equal to each other
neither List_A nor List_B have overridden the __eq__ method, so 
list.__eq__ will be used...


conclusion:
if they have equal elements in the same order, they will compare 
equal since they are, in fact, list's


Do you not get the same conclusion?

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


Re: checking if a list is empty

2011-05-12 Thread Terry Reedy

On 5/12/2011 3:37 PM, Terry Reedy wrote:

On 5/11/2011 8:26 AM, Roy Smith wrote:


I conclude that li == [] should have returned False. Either I'm not
understanding things correctly, or this is a bug.


The doc is wrong (and not only on this). I am working on a report with
suggested fixes. Will post number when finish.


http://bugs.python.org/issue12067

--
Terry Jan Reedy

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


Re: unicode by default

2011-05-12 Thread Ian Kelly
On Thu, May 12, 2011 at 2:42 PM, Terry Reedy  wrote:
> On 5/12/2011 12:17 PM, Ian Kelly wrote:
>> Right.  *Under the hood* Python uses UCS-2 (which is not exactly the
>> same thing as UTF-16, by the way) to represent Unicode strings.
>
> I know some people say that, but according to the definitions of the unicode
> consortium, that is wrong! The earlier UCS-2 *cannot* represent chars in the
> Supplementary Planes. The later (1996) UTF-16, which Python uses, can. The
> standard considers 'UCS-2' obsolete long ago. See
>
> https://secure.wikimedia.org/wikipedia/en/wiki/UTF-16/UCS-2
> or http://www.unicode.org/faq/basic_q.html#14

At the first link, in the section _Use in major operating systems and
environments_ it states, "The Python language environment officially
only uses UCS-2 internally since version 2.1, but the UTF-8 decoder to
"Unicode" produces correct UTF-16. Python can be compiled to use UCS-4
(UTF-32) but this is commonly only done on Unix systems."

PEP 100 says:

The internal format for Unicode objects should use a Python
specific fixed format  implemented as 'unsigned
short' (or another unsigned numeric type having 16 bits).  Byte
order is platform dependent.

This format will hold UTF-16 encodings of the corresponding
Unicode ordinals.  The Python Unicode implementation will address
these values as if they were UCS-2 values. UCS-2 and UTF-16 are
the same for all currently defined Unicode character points.
UTF-16 without surrogates provides access to about 64k characters
and covers all characters in the Basic Multilingual Plane (BMP) of
Unicode.

It is the Codec's responsibility to ensure that the data they pass
to the Unicode object constructor respects this assumption.  The
constructor does not check the data for Unicode compliance or use
of surrogates.

I'm getting out of my depth here, but that implies to me that while
Python stores UTF-16 and can correctly encode/decode it to UTF-8,
other codecs might only work correctly with UCS-2, and the unicode
class itself ignores surrogate pairs.

Although I'm not sure how much this might have changed since the
original implementation, especially for Python 3.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.7 Debian 6.0. Squeeze

2011-05-12 Thread Chen Wei
On Thu, May 12, 2011 at 12:03:26PM -0400, Jorge Romero wrote:
> Actually came back with some feedback to my own question.
> 
> The following repositories do the job:
> # /etc/apt/sources.list
> deb http://ftp.uk.debian.org/debian/ unstable main contrib non-free
> deb http://ftp.uk.debian.org/debian/ experimental main contrib non-free
> deb http://security.debian.org/ testing/updates main contrib

python2.7 is included in debian testing, so point the sources.list to
testing instead of unstable or experimental should also works.
deb http://ftp.uk.debian.org/debian/ testing main contrib non-free

> $ apt-get update
> $ apt-get install python2.7
> $ python --version
> Python 2.6.6
> $ python2.7 --version
> Python 2.7.1+
> 


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


Peculiar Behaviour of __builtins__

2011-05-12 Thread Aman Nijhawan
I was trying to call the builtin function min by using
getattr(__builtins__,'min')

This works at the interpretter prompt

However when I called it inside a module that was imported by another module
it fails and gives an attribute error

print getattr(__builtins__,'min')(range(20))
AttributeError: 'dict' object has no attribute 'min'

Also in the interpreter
>>>type(__builtins__)

but in my module

print type(__builtins__)


Can anyone help me understand whats going on here?


Thanks

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


Re: checking if a list is empty

2011-05-12 Thread Steven D'Aprano
On Thu, 12 May 2011 07:36:27 -0400, Roy Smith wrote:

> In article <[email protected]>,
>  Gregory Ewing  wrote:
> 
>> Roy Smith wrote:
>> >>If both are numbers, they are converted to a common type. Otherwise,
>> >>objects of different types always compare unequal
>> 
>> That's just the default treatment for unrelated types that don't know
>> anything about each other.
>> 
>> I would guess that the list's == method is asking "Is the other object
>> a list?", and since a subclass of list is also a list, it's happy and
>> goes on to compare the elements.
> 
> Well, that explains what's happening, but the behavior still doesn't
> match the docs.  Is this a bug or are the docs wrong?


The docs are incomplete.

You are missing two facts:

* The docs you are quoting refer only to built-in types. That it doesn't 
make so clear is a documentation bug.

* Talking about "different" and "same" types is ambiguous. It depends on 
how you compare types:

type(a) is type(b)

isinstance(a, type(b))

You are reading the docs as if the first comparison is the way to do it, 
but the second is usually preferred.

Any time you read something about "the same type", you should mentally 
add "(or an instance of a sub-class)" to it, unless explicitly told 
different. Whether it is better to add that parenthetical comment every 
time it is needed, or to assume that the read knows enough about object-
oriented programming to assume it, is an open question.

Me personally, I think it's part of the mental landscape that can be 
assumed, like C docs might state "dereference the pointer" without adding 
"(unless it is a nul pointer)" *every single time*.


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


Re: list equal to subclass of list?

2011-05-12 Thread Steven D'Aprano
On Thu, 12 May 2011 09:43:23 -0700, Ethan Furman wrote:

> MyList is a list -- just a more specific kind of list -- as can be seen
> from its mro; this is analogous to a square (2 sets of parallel lines
> joined at 90 degree angles, both sets being the same length) also being
> a rectangle (2 sets of parallel lines joined at 90 degree angles).

Possibly the worst analogy ever! *wink*

http://en.wikipedia.org/wiki/Circle-ellipse_problem

Also known as the square-rectangle problem.

A better analogy might be, Lassie is a dog, and Flipper is a dolphin, so 
they are different types of animal. But both dogs and dolphins are 
mammals, so in that sense, Lassie and Flipper are both mammals and 
therefore the same type of animal. It depends on what you mean by "type".



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


Re: Proper way to handle errors in a module

2011-05-12 Thread Steven D'Aprano
On Thu, 12 May 2011 15:26:27 -0500, Tycho Andersen wrote:

> On Thu, May 12, 2011 at 03:12:39PM -0500, Andrew Berg wrote:
>> On 2011.05.12 02:25 PM, MRAB wrote:
>> > You can raise an exception wherever you like! :-)
>> If I raise an exception that isn't a built-in exception, I get
>> something like "NameError: name 'HelloError' is not defined". I don't
>> know how to define the exception.
> 
> You'll have to define it, as you would anything else (exceptions are
> just regular "things"; in fact you can raise anything that's a class or
> instance).

Not quite.

>>> raise 42
Traceback (most recent call last):
  File "", line 1, in 
TypeError: exceptions must be classes or instances, not int

Not a very good error message, because 42 is an instance!

>>> isinstance(42, int)
True

In Python 3, you get a better error message, and further restrictions on 
what you can raise:

>>> raise 42
Traceback (most recent call last):
  File "", line 1, in 
TypeError: exceptions must derive from BaseException


In general, you should always subclass Exception rather than 
BaseException. There are, er, exceptions, but for error-handling you 
normally should inherit from Exception directly, or some sub-class like 
ValueError, KeyError, etc.




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


Re: list equal to subclass of list?

2011-05-12 Thread Ethan Furman

Steven D'Aprano wrote:

On Thu, 12 May 2011 09:43:23 -0700, Ethan Furman wrote:


MyList is a list -- just a more specific kind of list -- as can be seen
from its mro; this is analogous to a square (2 sets of parallel lines
joined at 90 degree angles, both sets being the same length) also being
a rectangle (2 sets of parallel lines joined at 90 degree angles).


Possibly the worst analogy ever! *wink*

http://en.wikipedia.org/wiki/Circle-ellipse_problem

Also known as the square-rectangle problem.

A better analogy might be, Lassie is a dog, and Flipper is a dolphin, so 
they are different types of animal. But both dogs and dolphins are 
mammals, so in that sense, Lassie and Flipper are both mammals and 
therefore the same type of animal. It depends on what you mean by "type".


I thought about using the mammal analogy instead, but geometry seemed 
simpler.  *sigh*  Oh, well, can't win 'em all!


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


Re: Proper way to handle errors in a module

2011-05-12 Thread Ben Finney
Andrew Berg  writes:

> So that's where that info is. I wasn't looking in the tutorial
> section.

Does this mean you haven't worked through the tutorial? Time to remedy
that.

-- 
 \ “You are welcome to visit the cemetery where famous Russian and |
  `\Soviet composers, artists, and writers are buried daily except |
_o__)   Thursday.” —Russian orthodox monastery, Moscow |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list equal to subclass of list?

2011-05-12 Thread Roy Smith
In article ,
 Ethan Furman  wrote:

> > [http://docs.python.org/library/stdtypes.html]
> > Objects of different types, except different numeric types and different 
> > string types, never compare equal
> 
> This part of the documentation is talking about built-in types, which 
> your MyList is not.
> 
> 
> > [http://docs.python.org/release/2.7/reference/expressions.html#notin]
> > objects of different types *always* compare unequal
> 
> Should probably have the word 'built-in' precede 'types' here, since 
> constructed objects can do whatever they have been told to do.

Changing the docs (in numerous places) to make it clear that this is 
only true of built-in types would indeed resolve the problem.  As it 
reads now, it's a general statement about ALL types, built-in or 
user-defined.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Peculiar Behaviour of __builtins__

2011-05-12 Thread Gabriel Genellina
En Thu, 12 May 2011 20:29:57 -0300, Aman Nijhawan   
escribió:



I was trying to call the builtin function min by using
getattr(__builtins__,'min')

This works at the interpretter prompt

However when I called it inside a module that was imported by another  
module

it fails and gives an attribute error


__builtins__ (note the final 's') is an implementation detail. You want  
the __builtin__ (no 's') module, renamed 'builtin' in Python 3.x


py> import __builtin__
py> builtin_min = __builtin__.min
py> builtin_min([8,2,5])
2

See http://docs.python.org/library/__builtin__.html

Note: using getattr with a literal name is not so useful. Better to use  
dot notation.



--
Gabriel Genellina

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


Re: Peculiar Behaviour of __builtins__

2011-05-12 Thread Gabriel Genellina
En Thu, 12 May 2011 22:59:24 -0300, Gabriel Genellina  
 escribió:


En Thu, 12 May 2011 20:29:57 -0300, Aman Nijhawan  
 escribió:



I was trying to call the builtin function min by using
getattr(__builtins__,'min')

This works at the interpretter prompt

However when I called it inside a module that was imported by another  
module

it fails and gives an attribute error


__builtins__ (note the final 's') is an implementation detail. You want  
the __builtin__ (no 's') module, renamed 'builtin' in Python 3.x


Should read "...renamed 'builtins' in Python 3.x, just to add to the  
confusion." :)



--
Gabriel Genellina

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


Re: Non Programming in python

2011-05-12 Thread Rustom Mody
On Wed, May 11, 2011 at 5:57 PM, Calvin Spealman wrote:

> If this is the "non-programming side of python" then maybe some of us have
> a lacking definition of what "programming" is.  My mechanic stilll has to
> check the tire pressure and I need to update the version number in PyPI.
>

O well you dont like the term 'non-programming'? As I said neither do I...

On May 10, 2011 12:46 PM, "rusi"  wrote:
>
> Sorry for a silly subject change: A better one will be welcome -- cant
> think of a name myself.
>
> Maybe another way of describing this list may be
1. Programming from 'inside' or 'under' python
and
2. The rest of it which is outside/surrounding the python interpreter

Because 1 is mostly called 'programming' and 2 has no name, 2 gets neglected
more than it should.

Or take any python book and browse the contents.  What will you find?
Python data structures, Python control structures, OOP in python, advanced
function topics, scopes, modules, exceptions etc -- almost all the 'inside'
stuff well organized, with the outside stuff strewn around in hard-to-find
corners of the index (if at all).

Does that reflect the reality of python's actual learning curve?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need Assistance on this program.

2011-05-12 Thread vijay swaminathan
Hi Tim.,

Thanks.. This works as I had expected.

are there any documentation for the subprocess.call method? I tried going
through the python doc but could not narrow down. I just wanted to know how
do I pass an arguement after invoking the command prompt?

Any thoughts on this pls?


On Thu, May 12, 2011 at 4:08 PM, Tim Golden  wrote:

> On 12/05/2011 11:29, vijay swaminathan wrote:
>
> <... snippet from code ...>
>  print 'Invoking Command Promptt..'
>#subprocess.call(["start", "/DC:\\PerfLocal_PAL",
> "scripts_to_execute.bat"], shell=True)
>subprocess.call(["start", "C:\\windows\\system32\\cmd.exe"], shell =
> True)
>self.status()
> 
>
> If you want to use start, use start /wait.
>
> But you don't have to:
>
> 
> import threading
> import time
> import subprocess
>
> def run_command (command):
>  #
>  # .call is shorthand for: start process and wait
>  # CREATE_NEW_CONSOLE prevents it from getting messed
>  #  up with the Python console
>  #
>  subprocess.call (
>[command],
>creationflags=subprocess.CREATE_NEW_CONSOLE
>  )
>
> t = threading.Thread (target=run_command, args=("cmd.exe",))
> t.start ()
>
> while t.is_alive ():
>  print "alive"
>  time.sleep (0.5)
>
> print "Thread is dead"
>
> 
>
>
> TJG
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


Re: generate properties code in class dynamically

2011-05-12 Thread JamesEM
On May 12, 10:04 pm, Terry Reedy  wrote:
> On 5/12/2011 9:11 AM, JamesEM wrote:
>
>
>
> > I would prefer to generate the properties code dynamically from the
> > keys of the dictionaries.
> > What I am looking for is something like:
>
> > class MyClass(object):
>
> >      def __init__(self):
> >          self.d = {}
> >          d['field1'] = 1.0
> >          d['field2'] = 'A'
> >          d['field3'] = [10.0,20.0,30.0]
> >          for f in d:
> >             create_property(f)
>
> > where create_property(f) dynamically creates the property code for
> > field f in MyClass.
>
> > Is this possible?
>
> Without actually trying, I am not sure, but I believe maybe (possibly
> version dependent). The init method is the wrong place. Create the
> properties exactly once, just after the class is created. It is possible
> to add functions to classes as attributes (instance methods) after they
> are created. The property decorators *might* require that they be
> invoked with the class body, I do not know. I would first try with
> property().
>
> Assuming dict name 'd' is fixed:
>
> def gsd(key):
>    def get(self):
>      return self.d[key]
>    def set(self, value):
>      self.d[key] = value
>    def del(self):
>      del self.d[key]
>    return get,set,del
>
> for key in fieldnames:
>    setattr(MyClass, key, property(*gsd(key)))
>
> For recent versions, this could be done within a class decorator, but
> that is only convenient syntactic sugar.
>
> --
> Terry Jan Reedy

Thanks for your help.
I tried the above for get and set which worked as desired. However,
the del did not seem to work for me (using python 2.6.5).
I hope I did not mistype anything, but it objects to def del with a
syntax error. I guess because del is a reserved word.
James
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode by default

2011-05-12 Thread jmfauth
On 12 mai, 18:17, Ian Kelly  wrote:

> ...
> to worry about encodings are when you're encoding unicode characters
> to byte strings, or decoding bytes to unicode characters


A small but important correction/clarification:

In Unicode, "unicode" does not encode a *character*. It
encodes a *code point*, a number, the integer associated
to the character.

jmf

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


Re: checking if a list is empty

2011-05-12 Thread rusi
Mathematics has existed for millenia.
Hindu-arabic numerals (base-10 numbers) have been known for about one
millennium
The boolean domain is only a 100 years old.
Unsurprisingly it is not quite 'first-class' yet: See
http://www.cs.utexas.edu/users/EWD/transcriptions/EWD10xx/EWD1070.html
[Lifted from http://c2.com/cgi/wiki?EqualVsTrueFalse ]


"In retrospect, one might be tempted to regard the introduction of
something as simple as the boolean domain as a minor invention, but I
think that that would be a grave mistake: it is a great invention
because, being so simple, it is such a powerful simplifier. It is of
the same level as the introduction of natural numbers, which enabled
us to add 3 to 5, regardless of whether we are adding apples or
pears."

"George Boole made a radical invention, so radical, in fact, that now,
more than a century later, the scientific community has not absorbed
it yet. (To stay with the metaphor: officially, boolean expressions
may have reached the status of first-class citizens, in practice —
because old habits and prejudices die hard— they are still the victims
of discrimination.) Let me give you a few examples."

"In the programming language FORTRAN, as conceived a century after
Boole published his invention, boolean expressions are allowed, but
there are no boolean variables! Their introduction into programming
had to wait until the design of ALGOL 60."


So, M Harris problem is that python could almost be a language for the
'masses' (whatever that might mean) were it not for warts like "l not
is empty" is shorten-able to just "l"

Dijkstra's problem (paraphrased) is that python, by choosing the
FORTRAN alternative of having a non-first-class boolean type, hinders
scientific/mathematical thinking/progress.

I tend to agree with Dijkstra's view that the boolean type should be
given more respect
except for the small fact that the computer's ALU is based on the
logic-arithmetic pun:
half-adder = xor
(half)-carry = and
-- 
http://mail.python.org/mailman/listinfo/python-list