Re: "Strong typing vs. strong testing"

2010-10-13 Thread Gregory Ewing

RG wrote:
Even an interest 
rate of 0.1 radians makes sense if for some unfathomable reason you want 
to visualize your interest payment as the relative length of a line 
segment and an arc.


It could even be quite reasonable if you're presenting it
as a segment of a pie graph.

For what it's worth, the GST rate here recently increased
from 0.7853 to 0.9425 radians. :-)

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


Re: Wrong default endianess in utf-16 and utf-32 !?

2010-10-13 Thread jmfauth
On 12 oct, 22:00, John Machin  wrote:
> jmfauth  gmail.com> writes:
>
> > When an endianess is not specified, (BE, LE, unmarked forms),
> > the Unicode Consortium specifies, the default byte serialization
> > should be big-endian.
>
> > Seehttp://www.unicode.org/faq//utf_bom.html
> > Q: Which of the UTFs do I need to support?
> > and
> > Q: Why do some of the UTFs have a BE or LE in their label,
> > such as UTF-16LE?
>
> Sometimes it is necessary to read right to the end of an answer:
>
> Q: Why do some of the UTFs have a BE or LE in their label, such as UTF-16LE?
>
> A: [snip] the unmarked form uses big-endian byte serialization by default, but
> may include a byte order mark at the beginning to indicate the actual byte
> serialization used.



Well, English is not my native language, however I think I read it
correctly.

My question had nothing to do with the BOM, the encoding/decoding
or the BOM inclusion. My question was:

"What should I understand by "utf-16"?  "utf-16-le" or "utf-16-be"?

And Antoine gave an answer.

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


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Gregory Ewing

Dann Corbit wrote:

But in a very real sense it is a measure of rotation.  We could call it 
a special measure, sort of like the way that e is a special base 
compared to all others.


That's not the only thing that radians are useful for, though.
Consider a weight bobbing up and down on a spring, or anything
else with periodic behaviour. It's common to represent its
position in the oscillation cycle in terms of an angle, even
though nothing is actually rotating.

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


Re: Tkinter: Exception RuntimeError: 'maximum recursion depth exceeded'

2010-10-13 Thread Olaf Dietrich
Jeff  Hobbs :
> On Oct 12, 9:43 am, o...@dtrx.de (Olaf Dietrich) wrote:
>>
>> After some somewhat heavy mouse action inside the
>> canvas (with the left button pressed), the application throws:
>>
>> | Exception RuntimeError: 'maximum recursion depth exceeded' in > method PhotoImage.__del__ of > 
>> ignored
>> | Exception in Tkinter callback
[...]
>> (and similiar ones)
>>
>> This error can be provoked faster by setting the recursion limit
>> to lower values (e.g. 400 as in the comment above).
>>
>> Is there anything I can do (apart from increasing the recursion
>> limit) to avoid this exception? Can I improve anything in the
>> script above to make the whole thing more robust?
> 
> It seems very heavy-handed to create 1-pixel images for drawing onto
> the canvas.  Any reason not to use something lighter weight?

The example was _heavily_ simplified; originally, there was
a background (e.g. gray-scale) image and I was drawing lines or
other shapes onto that background that should appear in color
and semi-transparent on top of the background. Additionally,
both background and foreground can be zoomed and scrolled, and
there should be a pixel-by-pixel correspondence between the
(zoomed) background pixels and the semi-transparent shapes
in the foreground (as opposed to overlayed vector graphics).
I could not find a more light-weight solution for these
requirements.


> I suspect the "self.root.update()" is the problem.  Try
> update_idletasks() instead, or to even avoid it if possible.  You
> don't want to call update in the event loop, because you are likely
> reprocessing from the same call, causing the recursion.

Indeed, Tk/Toplevel/Canvas.update() seems to be at the
center of the problem.

If I replace update() by update_idletasks(), the problem
disappears, but unfortunately, considerably fewer events
are recorded on the canvas (when connecting the pixels with
lines, the lines become much longer with update_idletasks()
than with update()). If I remove both update() and
update_idletasks(), things work similarly as with
update_idletasks() (the display is only marginally slower
than with update_idletasks()).

I wonder if there is any compromise between update()
and update_idletasks():

* update(): smooth lines but recursion exception
* update_idletasks(): non-smooth lines without exceptions


Thanks a lot for your help
Olaf
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-13 Thread RG
In article <8hl3grfh2...@mid.individual.net>,
 Gregory Ewing  wrote:

> RG wrote:
> > Even an interest 
> > rate of 0.1 radians makes sense if for some unfathomable reason you want 
> > to visualize your interest payment as the relative length of a line 
> > segment and an arc.
> 
> It could even be quite reasonable if you're presenting it
> as a segment of a pie graph.

Good point.

> For what it's worth, the GST rate here recently increased
> from 0.7853 to 0.9425 radians. :-)

:-)

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


Re: "Strong typing vs. strong testing"

2010-10-13 Thread RG
In article <8hl2ucfdv...@mid.individual.net>,
 Gregory Ewing  wrote:

> Tim Bradshaw wrote:
> > In general any function 
> > which raises its argument to more than one power ...  doesn't make
> > much sense if its argument has units.
> 
> That's not true. Consider the distance travelled by a
> falling object: y(t) = y0 + v0*t + 0.5*a*t**2. Here t has
> dimensions of time, and it's being raised to different
> powers in different terms. It works because the
> coefficents have dimensions too, and all the terms end up
> having the same dimensions.

This reminds me of back when I was a kid and my dad was trying to teach 
me basic physics.  He kept saying that the acceleration of gravity was 
9.8 meters per second squared and I just couldn't wrap my brain around 
what it meant to square a second.

Now that I think about it, I still can't.  :-)

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


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Tim Bradshaw

On 2010-10-13 02:00:46 +0100, BartC said:


But what exactly *is* this number? Is it 0.25, 1.57 or 90?


Its pi/2, the same way 90% is 9/10.




I can also write 12 inches, 1 foot, 1/3 yards, 1/5280 miles, 304.8 mm 
and so on. They are all the same number, roughly 1/13100 of the 
polar circumference of the Earth.


They are not numbers they are lengths.

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


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Chris Rebert
On Wed, Oct 13, 2010 at 12:31 AM, RG  wrote:

> This reminds me of back when I was a kid and my dad was trying to teach
> me basic physics.  He kept saying that the acceleration of gravity was
> 9.8 meters per second squared and I just couldn't wrap my brain around
> what it meant to square a second.
>
> Now that I think about it, I still can't.  :-)

Allow me to warp both our minds by *cubing* one then:
http://en.wikipedia.org/wiki/Jerk_%28physics%29

Cheers,
Chris
--
There's also a [[Yank (physics)]]. Therefore, a Yankee is...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Compiling as 32bit on MacOSX

2010-10-13 Thread Gregory Ewing

Philip Semanchuk wrote:


Hi Greg,
Are you talking about compiling Python itself or extensions?


I've managed to get Python itself compiled as 32 bit,
and that also seems to take care of extensions built
using 'python setup.py ...'.

I'm mainly concerned about non-Python libraries that
get wrapped by the extensions, of which I've built up
quite a collection over the years. Currently I'm having
to keep a careful eye out when building them to make
sure they don't get compiled with the wrong architecture,
since gcc's natural inclination is to default to 64 bit
whenever it's available.

So I was wondering if there was some way of globally
changing that default that doesn't rely on compiler
options getting passed correctly through the many and
varied layers of build technology that one comes across.
But from what I've seen so far, it seems not.

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


Re: Compiling as 32bit on MacOSX

2010-10-13 Thread Gregory Ewing

Jason Swails wrote:

Try setting the compiler itself as "gcc -m32"


You mean by setting CC? That's a cunning plan -- I'll
give it a try.

On a related note, according to the man page for Apple's
gcc, you're supposed to be able to use both '-arch i386'
and '-arch x86_64' at the same time and get fat binaries.
That would actually be my preferred option, because then
I wouldn't have to go back and rebuild all my libraries
if I decide to switch to 64 bit in the future.

But I can't seem to get it to work -- it just uses the
last architecture specified. Has anyone successfully done
this? Is there some trick to it that I've missed?

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


Re: Compiling as 32bit on MacOSX

2010-10-13 Thread Diez B. Roggisch
Gregory Ewing  writes:

> Philip Semanchuk wrote:
>
>> Hi Greg,
>> Are you talking about compiling Python itself or extensions?
>
> I've managed to get Python itself compiled as 32 bit,
> and that also seems to take care of extensions built
> using 'python setup.py ...'.
>
> I'm mainly concerned about non-Python libraries that
> get wrapped by the extensions, of which I've built up
> quite a collection over the years. Currently I'm having
> to keep a careful eye out when building them to make
> sure they don't get compiled with the wrong architecture,
> since gcc's natural inclination is to default to 64 bit
> whenever it's available.
>
> So I was wondering if there was some way of globally
> changing that default that doesn't rely on compiler
> options getting passed correctly through the many and
> varied layers of build technology that one comes across.
> But from what I've seen so far, it seems not.

If all you have is a fat-binary, you can still work with that using the
lipo-tool to remove those architectures you are not interested in.

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


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Rob Warnock
RG   wrote:
+---
| This reminds me of back when I was a kid and my dad was trying to teach 
| me basic physics.  He kept saying that the acceleration of gravity was 
| 9.8 meters per second squared and I just couldn't wrap my brain around 
| what it meant to square a second.
| 
| Now that I think about it, I still can't.  :-)
+---

Write it our longhand and it's easier to grok:

9.8 m/s^2 ==> 9.8 m/(s*s) ==> 9.8 m/(s*s) ==>
(9.8 meters per second) per second.
 \   /
  \__ speed added __/   per second


-Rob

-
Rob Warnock 
627 26th Avenue http://rpw3.org/>
San Mateo, CA 94403 (650)572-2607

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


Re: "Strong typing vs. strong testing"

2010-10-13 Thread RG
In article ,
 r...@rpw3.org (Rob Warnock) wrote:

> RG   wrote:
> +---
> | This reminds me of back when I was a kid and my dad was trying to teach 
> | me basic physics.  He kept saying that the acceleration of gravity was 
> | 9.8 meters per second squared and I just couldn't wrap my brain around 
> | what it meant to square a second.
> | 
> | Now that I think about it, I still can't.  :-)
> +---
> 
> Write it our longhand and it's easier to grok:
> 
> 9.8 m/s^2 ==> 9.8 m/(s*s) ==> 9.8 m/(s*s) ==>
> (9.8 meters per second) per second.
>  \   /
>   \__ speed added __/   per second

Oh, that part I get.  It's the abstract squared second that's still a 
deep mystery to me.  A squared length is easily visualized.  But 
according to relativity space and time are just two aspects of the same 
thing, so a squared second should make some kind of physical sense.

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


Re: subprocess.check_call() fails ... but only on my production machine

2010-10-13 Thread Tim Golden

On 12/10/2010 14:31, Chris Curvey wrote:

I've got a python program running on windows that executes a command-
line script.  The command being executed is:


print cmd

"C:\Program Files\ImageMagick-6.6.1-Q16\convert.exe" -density 72x72 "c:
\temp\choicepoint 2010-01 Stmt_p1.pdf" -quiet -region (612.0x70.0+0+0 -
blur 0x3) -region (612.0x709.0+0+83.0 -blur 0x3)  "\\fs4\w
\13\132651\BILLING_PROOFS\132651_choicepoint 2010-01 Stmt_p1_r1.pdf"


subprocess.check_call(cmd, shell=True)


if I  run the command thru python subprocess.check_call() on my
Windows 7 (development) machine, it works fine.
if I run the command in a command in a command window on my windows
2007 server (production) machine, it works fine.
if I run the command thru  python subprocess.check_call() on my
Windows 2007 server (production) machine, it fails.

I'm running both the Python script and the command window as the same
user.  Can anyone give me a hint as to what might be happening...or a
way to get more information about what the error is?  (All I get is
"Command returned non-zero exit status 1")


The subprocess code has changed quite a bit between
versions. Can you confirm which version of Python you're
using?

FWIW, subprocess.check_call is a lightweight wrapper around subprocess.call
so running the same code as subprocess.call should give you more 
information.


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


Re: Help needed - To get path of a directory

2010-10-13 Thread Bishwarup Banerjee
Dear Emmanuel,

Thank you for your reply.
Actually what I want to do is, at the run time I want to know the location
of a specific directory.
Then I will add some file name to the path and load the file.
The directory can reside in any drive, depending on the user.

With Warm Regards,


On Wed, Oct 13, 2010 at 12:03 PM, Emmanuel Surleau <
emmanuel.surl...@gmail.com> wrote:

> > Dear All,
> >
> > I want to get the absolute path of the Directory I pass explicitly. Like
> >
> > functionName("\abcd").
> > I should pass the name of the directory and the function should search
> for
> > it in the Hard drives and return me the full path of location on the
> drive.
> > I tried using os.path, but didn't succeed.
> >
> > I am using python 2.5 on windows platform.
> > It will be very kind of you if you can guide me on this.
>
> What is your path relative to? The python file? The working directory? Can
> it
> be absolute? Or do you actually intend to "search for it in the hard
> drives"
> because you don't know where it is?
>
> Cheers,
>
> Emm
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I don't get why sys.exit(1) doesn't exit the while loop in the follow case

2010-10-13 Thread Arnaud Delobelle
Nobody  writes:

> On Mon, 11 Oct 2010 05:42:39 -0700, Ethan Furman wrote:
>
If I'm catching exceptions in order to perform clean-up, I'll use a bare
except and re-raise the exception afterwards. In that situation, a bare
except is usually the right thing to do.
>>> 
>>> Wrong way to do it.
>> 
>> What, then, is the right way to do it?
>
> I presume that he's referring to "finally". Which is reasonable enough
> given what I wrote, but isn't always convenient.
>
> My point was that bare excepts aren't a problem if you're going to
> re-raise the exception.

If I understand correctly, there is a big difference between bare except
and finally:

>>> def f(x):
... try:
... if x:
... raise ValueError("x should be falsy")
... except:
... print("bare except")
... raise
... finally:
... print("finally")
... 
>>> f(0)
finally
>>> f(1)
bare except
finally
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 4, in f
ValueError: x should be falsy

The finally: clause is always executed, whereas the bare except: clause
is only executed if an exception was raised in the try: clause.

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


Re: Compiling as 32bit on MacOSX

2010-10-13 Thread Ned Deily
In article <8hl75sf6j...@mid.individual.net>,
 Gregory Ewing  wrote:
> On a related note, according to the man page for Apple's
> gcc, you're supposed to be able to use both '-arch i386'
> and '-arch x86_64' at the same time and get fat binaries.
> That would actually be my preferred option, because then
> I wouldn't have to go back and rebuild all my libraries
> if I decide to switch to 64 bit in the future.
> 
> But I can't seem to get it to work -- it just uses the
> last architecture specified. Has anyone successfully done
> this? Is there some trick to it that I've missed?

You'll also need to specify the appropriate SDK using Apple's gcc 
-sysroot option.

-- 
 Ned Deily,
 n...@acm.org

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


Re: Performance evaluation of HTTPS library

2010-10-13 Thread Ashish
On Oct 13, 11:11 am, Ashish  wrote:
> On Oct 12, 6:33 pm, Antoine Pitrou  wrote:> On Tue, 12 
> Oct 2010 05:40:43 -0700 (PDT)
>
> > Ashish Vyas  wrote:
> > > Another observation that I have made is with 10 parallel HTTPS connection 
> > > each
> > > trying 1 transaction per second from 2 different machines (effectively 
> > > same load
> > > on server), the response time is again reducing to .17 secs.
> > > However if I run two instances of the tool with 10 parallel HTTPS 
> > > connection
> > > each trying 1 transaction per second from from same machine, the response 
> > > time
> > > is again shooting up to 1.1 seconds.
>
> > Is the client machine at 100% CPU when you do that?
>
> With HTTP, I see client CPU at appx. 97%. However with HTTPS, it stays
> at 53-55%.
>
> > > So the question is does anyone here have any idea or some data about 
> > > performance
> > > limitation of HTTPS implementation in Python 3.1?
>
> > Which API are you using? urlopen()?
> > The HTTPS implementation is basically the same as the HTTP
> > implementation, except for the additional SSL layer. So if indeed
> > Python is responsible for the slowdown, it may be because of excessive
> > overhead brought by the SSL layer.
>
> I am doing something like this:-
>
> self.conn = AsyncHTTPSConnection(self.URL, HTTPS_PORT)
>
> self.conn.putrequest('POST', WEBSERVER_IP)
> self.conn.putheader('Cookie', cookie)
> self.conn.putheader('Content-Length', reqLen)
> ..
> self.conn.endheaders()
> self.conn.send(str.encode(reqest))
>
> and AsyncHTTPSConnection class is something like this:-
>
> class AsyncHTTPSConnection(client.HTTPConnection):
>     default_port = HTTPS_PORT
>     def __init__(self, host, port=HTTPS_PORT, key_file=None,
> cert_file=None,
>                      strict=None,
> timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
>         """ Init has same eparameters as HTTPSConnection. """
>         client.HTTPConnection.__init__(self, host, port, strict,
> timeout)
>         self.key_file = key_file
>         self.cert_file = cert_file
>
>     def connect(self):
>         try:
>             log.mjLog.LogReporter ("Model", "info",
> "AsyncHTTPSConnection::connect trying to connect... "+ str(self.host)
> + ":"+ str(self.port))
>             sock = socket.create_connection((self.host, self.port),
> self.timeout)
>             sock2 = ssl.wrap_socket(sock, self.key_file,
> self.cert_file)
>             self.sock = CBSocket(sock2)
>         except:
>             log.mjLog.LogReporter ("Model", "critical",
> "AsyncHTTPSConnection::connect Failed to connect to the GWS")
>
> > It would be nice if you tried the just-released Python 3.2 alpha,
> > because some changes have been made to the SSL 
> > wrapper:http://python.org/download/releases/3.2/
>
> Let me try to use this, I will come back with my observations.

Well, I tried python3.2a2 and the average response time for 20 HTTPS
tps reduced from about 1.1 seconds to about .97 seconds.
This is a noticeable change but not enough I feel.
Also when I tried running same test client on XEON, I am able to see
average response time appx. 0.23 seconds.

>
> > Also, there's a feature request to reduce overhead of SSL
> > connections, but it needs implementing:http://bugs.python.org/issue8106
>
> Well good to know this. Do we have any date when this will be
> available? I feel like contributing to this but kind of over occupied
> with several activities right now.
>
>
>
> > Regards
>
> > Antoine.
>
> Thanks a lot,
> Ashish

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


a test posting

2010-10-13 Thread Ng Spim
Proin molestie porttitor magna, sed ullamcorper nibh eleifend non. Ut
posuere condimentum aliquet. Sed luctus aliquam est, vitae sollicitudin
diam adipiscing non. Fusce quis nulla vitae odio pulvinar condimentum.
Curabitur hendrerit, nisl ut interdum tincidunt, ligula lorem
consectetur elit, non fermentum lectus ligula eget eros. Morbi eleifend
malesuada diam, in accumsan augue iaculis sed. Phasellus est nunc,
tristique id sagittis id, pharetra interdum nisl. Aenean pharetra
vestibulum ipsum, consectetur scelerisque ipsum rhoncus suscipit. Nam
leo ipsum, fermentum vel placerat eget, pulvinar in eros. Class aptent
taciti sociosqu ad litora torquent per conubia nostra, per inceptos
himenaeos. Quisque ipsum enim, interdum scelerisque adipiscing ut,
vehicula vel orci. Aliquam eros dui, pretium nec tempor sit amet,
rhoncus at arcu. Donec fringilla eleifend turpis, quis mollis augue
lobortis condimentum. Etiam eu diam sed velit fringilla sagittis. Morbi
vestibulum sem nec mi vulputate porttitor. Pellentesque habitant morbi
tristique senectus et netus et malesuada fames ac turpis egestas.
Pellentesque mi orci, porta ut lacinia sit amet, rutrum ut augue.
Phasellus metus nibh, vestibulum quis fermentum sed, dapibus ac dolor.
Nunc mauris nisl, tristique ut commodo sit amet, sodales ac urna. Etiam
mattis rhoncus bibendum.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Standardizing RPython - it's time.

2010-10-13 Thread Carl Friedrich Bolz
Hi John,

John Nagle  animats.com> writes:

>  All attempts to make the dialect defined by CPython significantly
> faster have failed.  PyPy did not achieve much of a speed
> improvement over CPython, and is sometimes slower.

This is not true. While PyPy is indeed sometimes slower than CPython, there is a
significant speedup for many synthetic and real-life benchmarks. PyPy with a JIT
is up to 20 times faster than CPython for synthetic benchmarks like richards,
but still something like 6 times faster for Django. It also beats Psyco in
almost all benchmarks. For detailed measurements, please visit our benchmarking
site: http://speed.pypy.org

All these numbers are also only the current state, PyPy is still continuously
improving.

Cheers,

Carl Friedrich

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


Re: Performance evaluation of HTTPS library

2010-10-13 Thread Stefan Behnel

Ashish Vyas, 12.10.2010 14:40:

When I send request using HTTP, I am able to reach 1 transaction (request sent,
response rcvd and validated.) per second from 20 parallel connections easily.
Average response time shown is about 0.15 seconds.
However, when I send request using HTTPS, I am seeing that the response time
shown by tool goes to 1.1 seconds for same 20 parallel connection each trying 1
transaction per second.


You shouldn't overestimate the performance requirements for SSL/TLS support 
inside of the server application itself, simply because it's not used that 
much in real world deployments.


It's actually very common to use a proxy to handle HTTPS traffic, and to 
forward the requests as plain HTTP to the "real" server. Separating the two 
gives you more freedom in your deployment (e.g. you can deploy the HTTPS 
proxy locally or on an entirely different machine at a suitable place in 
the network architecture), and makes your server generally more scalable. 
You can additionally use the HTTPS proxy machine to distribute the normal 
HTTP load over multiple server instances. There's even dedicated networking 
hardware for SSL/TLS proxying if you need it.


Stefan

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


Re: [Python-ideas] [Python-Dev] Inclusive Range

2010-10-13 Thread Antoon Pardon
On Tue, Oct 12, 2010 at 01:50:47PM -0400, Terry Reedy wrote:

> >That seems to be an undocumented feature. I didn't know it was possible
> >to use extra parameters after key in __getitem__.
> 
> They never get passed, and as I said above, should not have been
> there in the version I posted. Sorry for the noise. The actual point
> is that keys can be tuples and tuples can contain a slice and other
> info.

All right, I understand where your going with this.

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


Re: Performance evaluation of HTTPS library

2010-10-13 Thread Antoine Pitrou
On Wed, 13 Oct 2010 02:12:21 -0700 (PDT)
Ashish  wrote:
> >
> > > Is the client machine at 100% CPU when you do that?
> >
> > With HTTP, I see client CPU at appx. 97%. However with HTTPS, it stays
> > at 53-55%.

And is the server at 100% CPU then?
If the client is not at 100% CPU, it shouldn't be the bottleneck,
unless you have something wrong in the client implementation.

> >             sock = socket.create_connection((self.host, self.port),
> > self.timeout)
> >             sock2 = ssl.wrap_socket(sock, self.key_file,
> > self.cert_file)
> >             self.sock = CBSocket(sock2)

What is CBSocket? What happens if you just write:
self.sock = sock2

> > > Also, there's a feature request to reduce overhead of SSL
> > > connections, but it needs implementing:http://bugs.python.org/issue8106
> >
> > Well good to know this. Do we have any date when this will be
> > available? I feel like contributing to this but kind of over occupied
> > with several activities right now.

Probably not in Python 3.2 anyway. But given your client isn't at 100%
CPU when you launch your HTTPS test, it might not make a lot of
difference.

Regards

Antoine.


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


Re: Performance evaluation of HTTPS library

2010-10-13 Thread Ashish
On Oct 13, 2:36 pm, Stefan Behnel  wrote:
> Ashish Vyas, 12.10.2010 14:40:
>
> > When I send request using HTTP, I am able to reach 1 transaction (request 
> > sent,
> > response rcvd and validated.) per second from 20 parallel connections 
> > easily.
> > Average response time shown is about 0.15 seconds.
> > However, when I send request using HTTPS, I am seeing that the response time
> > shown by tool goes to 1.1 seconds for same 20 parallel connection each 
> > trying 1
> > transaction per second.
>
> You shouldn't overestimate the performance requirements for SSL/TLS support
> inside of the server application itself, simply because it's not used that
> much in real world deployments.
>
> It's actually very common to use a proxy to handle HTTPS traffic, and to
> forward the requests as plain HTTP to the "real" server. Separating the two
> gives you more freedom in your deployment (e.g. you can deploy the HTTPS
> proxy locally or on an entirely different machine at a suitable place in
> the network architecture), and makes your server generally more scalable.
> You can additionally use the HTTPS proxy machine to distribute the normal
> HTTP load over multiple server instances. There's even dedicated networking
> hardware for SSL/TLS proxying if you need it.
>
> Stefan

Yes, I absolutely agree to you that the server shall also have similar
overhead when HTTPS is used in place of HTTP. Thanks for suggesting
the HTTPS proxy box.

However, my problem here is:-

client on XEON machine sending req over HTTPS:average response
time ~= .2 secs
client on P4 machine sending req over  HTTP:  average response
time ~= .15 secs
client on P4 machine sending req over HTTPS:  average response
time ~= 1.1 secs

And I understand that until we have the feature implementation of
issue8106 as pointed out by Antoine, we may see no further improvement
on 1.1 secs (or .97 secs with 3.2a2) that I see.

Kindly confirm if my above conclusion is correct.

Thanks
Ashish.

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


Re: Tkinter: Exception RuntimeError: 'maximum recursion depth exceeded'

2010-10-13 Thread Lawrence D'Oliveiro
In message , Olaf Dietrich wrote:

> If I replace update() by update_idletasks(), the problem
> disappears, but unfortunately, considerably fewer events
> are recorded on the canvas (when connecting the pixels with
> lines, the lines become much longer with update_idletasks()
> than with update()). If I remove both update() and
> update_idletasks(), things work similarly as with
> update_idletasks() (the display is only marginally slower
> than with update_idletasks()).

How about simply avoiding recursive updates.

Add this line to your __init__ method:

self.reentered = False

In your viewdata method, put this at the start:

save_reentered = self.reentered
self.reentered = True

and this at the end:

self.reentered = save_reentered

while the update call becomes conditional on not being reentered:

if not save_reentered:
self.root.update()

Of course, this is all a total guess, I really know nothing about TKinter. 
:)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Rob Warnock
RG   wrote:
+---
| r...@rpw3.org (Rob Warnock) wrote:
| > Write it our longhand and it's easier to grok:
| > 9.8 m/s^2 ==> 9.8 m/(s*s) ==> 9.8 m/(s*s) ==>
| > (9.8 meters per second) per second.
| >  \   /
| >   \__ speed added __/   per second
| 
| Oh, that part I get.  It's the abstract squared second that's still a 
| deep mystery to me.
+---

As far as I know, there is no "abstract squared second" anywhere,
other than in formulae in which collecting the dimensions (as above)
ends up having an exponent of "2". That is, acceleration really *is*
"(distance / s) / s". It only gets to be "distance/(s^2)" when you
collect terms.

+---
| A squared length is easily visualized.  But according to relativity
| space and time are just two aspects of the same thing, so a squared
| second should make some kind of physical sense.
+---

Why should it?!? If you look way under the covers, I suspect that even
the "c^2" in "E = mc^2" is a "collected" term in the above sense [that is,
if I recall my classes in introductory special relativity correctly].


-Rob

-
Rob Warnock 
627 26th Avenue http://rpw3.org/>
San Mateo, CA 94403 (650)572-2607

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


Using csv.DictReader with \r\n in the middle of fields

2010-10-13 Thread pstatham
Hello everyone!

Hopefully this will interest some, I have a csv file (can be
downloaded from http://www.paulstathamphotography.co.uk/45.txt) which
has five fields separated by ~ delimiters. To read this I've been
using a csv.DictReader which works in 99% of the cases. Occasionally
however the description field has errant \r\n characters in the middle
of the record. This causes the reader to assume it's a new record and
try to read it.

Here's the code I had

import csv

fields = ["PROGTITLE", "SUBTITLE", "EPISODE", "DESCRIPTION", "DATE"]
delim= '~'

lineReader   = csv.DictReader(open('45.txt', 'rbU'),
delimiter=delim,fieldnames=fields)

def FormatDate(date):
return date[6:10] +"-" +date[3:5] + "-" +date[0:2]

channelPrograms = []

for row in lineReader:
row["DATE"] = FormatDate(row["DATE"])
channelPrograms.append(row)

Which when run would give me an error as it was trying to pass a
NoneType to the FormatDate method, which obviously couldn't handle it.

I'd like to find a way to read this record correctly despite the \r
\n's in the middle of the description. The problem is I can't change
the behaviour in which it reads a record.

For the moment I've had to resort to extending the csv.DictReader and
overriding the next() method to set the number of fields versus the
number of values, if they're not equal I don't add those lines to my
list of records.

import csv

class ChanDictReader(csv.DictReader):
def __init__(self, f, fieldnames=None, restkey=None, restval=None,
 dialect="excel", *args, **kwds):
csv.DictReader.__init__(self, f, fieldnames, restkey, restval,
 dialect, *args, **kwds)
self.lf = 0
self.lr = 0

def next(self):
if self.line_num == 0:
# Used only for its side effect.
self.fieldnames
row = self.reader.next()
self.line_num = self.reader.line_num

# unlike the basic reader, we prefer not to return blanks,
# because we will typically wind up with a dict full of None
# values
while row == []:
row = self.reader.next()
d = dict(zip(self.fieldnames, row))
self.lf = len(self.fieldnames)
self.lr = len(row)
if self.lf < self.lr:
d[self.restkey] = row[self.lf:]
elif self.lf > self.lr:
for key in self.fieldnames[self.lr:]:
d[key] = self.restval
return d

fields = ["PROGTITLE", "SUBTITLE", "EPISODE", "DESCRIPTION", "DATE"]
delim= '~'

lineReader   = ChanDictReader(open('45.txt', 'rbU'),
delimiter=delim,fieldnames=fields)

def FormatDate(date):
return date[6:10] +"-" +date[3:5] + "-" +date[0:2]

channelPrograms = []

for row in lineReader:
print "Number of fields: " + str(lineReader.lf) + " Number of
values: " + str(lineReader.lr)
if lineReader.lf == lineReader.lr:
row["DATE"] = FormatDate(row["DATE"])
channelPrograms.append(row)

Anyone have any ideas? :o)

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


optparser: how to register callback to display binary's help

2010-10-13 Thread hiral
Hi,

I want to display help message of python script and then display help
message from the binary file (which also supports -h option):

Assumptions:
1) 'mybinary' - is linux executable file which supports '-h' and on '-
h' option it displays the help message
2) myscript.py - when passing '-h' option want to call 'mybinary -h'
and display help messages of both script and binary.

Code:

from optparse import OptionParser
[...]
parser = OptionParser()
parser.add_option("-e", "--execute", dest="file",
  help="Execute binary", metavar="FILE")
(options, args) = parser.parse_args()
if options.file:
subprocess.call(options.file)


Requirement:
$ python myscript.py -h



Thank you in advance.
-Hiral
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: optparser: how to register callback to display binary's help

2010-10-13 Thread Michele Simionato
Here is a solution using plac (http://pypi.python.org/pypi/plac) and
not OptionParse, in the case
the Linux underlying command is grep:

import subprocess
import plac

@plac.annotations(help=('show help', 'flag', 'h'))
def main(help):
if help:
script_usage = plac.parser_from(main).format_help()
po = subprocess.Popen(['grep', '-h'], stderr=subprocess.PIPE)
grep_usage = po.stderr.read()
print script_usage
print grep_usage
main.add_help = False

if __name__ == '__main__':
plac.call(main)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-13 Thread BartC


"RG"  wrote in message 
news:rnospamon-ee76e8.18291912102...@news.albasani.net...

In article ,
"BartC"  wrote:

"RG"  wrote in message



> Likewise, all of the following are the same number written in different
> notations:
>
> pi/2
> pi/2 radians
> 90 degrees
> 100 gradians
> 1/4 circle
> 0.25 circle
> 25% of a circle
> 25% of 2pi
>
> See?

But what exactly *is* this number? Is it 0.25, 1.57 or 90?


It's an irrational number, so it cannot be written out exactly.  But
it's approximately 1.57.


My money would have been on 0.25, based on using 1.0 for a 360° circular 
angle. It seems far more attractive than using the arbitrary-looking 6.28...


(I understand that when 2 pi is used, this works more naturally in certain 
mathematical formulae.)


I can also write 12 inches, 1 foot, 1/3 yards, 1/5280 miles, 304.8 mm and 
so

on. They are all the same number, roughly 1/13100 of the polar
circumference of the Earth.


These aren't numbers, these are lengths.  They correspond to a physical
thing out there in the real world.  Numbers don't.

This does depend on the actual size of an arbitrary circle, but that 
seems

little different from the choice of 0.25, 1.57 or 90 for your quarter
circle.


Why does it seem "little different"?  That is exactly the difference.
What you're doing in your "1/13100 of the polar circumference of the
Earth" is taking the number 1/13100 and using it to describe a
length.


My example was based on the fact that a metre was once defined as 1/1000 
of the equator-pole distance. They were taking the number 1/1000 and 
using it to describe a length (of a unit called a metre).


Above, you're using 1/(two pi), and using it to describe an angle (of a unit 
called a radian).


The only difference is that on a different planet, they would almost 
certainly use a different unit for length, but would quite possibly still 
use radians for angles, amongst others units.


--
Bartc 


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


Re: PEP 249 (database api) -- executemany() with iterable?

2010-10-13 Thread Jon Clements
On 12 Oct, 20:21, "J. Gerlach"  wrote:
> Am 12.10.2010 17:10, schrieb Roy Smith:
>
> > [A]re there any plans to update the api to allow an iterable instead of
> > a sequence?
>
> sqlite3 (standard library, python 2.6.6., Windows 32Bit) does that already::
>
> import sqlite3 as sql
>
> connection = sql.connect(":memory:")
>
> cursor = connection.execute("""
>     CREATE TABLE test (
>         id INTEGER PRIMARY KEY AUTOINCREMENT,
>     text TEXT)
>     ;""")
> connection.commit()
> cursor.executemany("""
>     INSERT INTO test (text) VALUES ( ? );
>     """,
>     # A generator expression - delivers one row at a time
>     ( ("hello nr %03d!" % i,) for i in xrange(100)))
> connection.commit()
> cursor.execute("SELECT * FROM test")
>
> for id_, text in cursor.fetchall():
>     print text, id_

What happens if you do itertools.repeat(0) instead of xrange(100) ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Performance evaluation of HTTPS library

2010-10-13 Thread Ashish
On Oct 13, 3:19 pm, Antoine Pitrou  wrote:
> On Wed, 13 Oct 2010 02:12:21 -0700 (PDT)
>
> Ashish  wrote:
>
> > > > Is the client machine at 100% CPU when you do that?
>
> > > With HTTP, I see client CPU at appx. 97%. However with HTTPS, it stays
> > > at 53-55%.
>
> And is the server at 100% CPU then?
> If the client is not at 100% CPU, it shouldn't be the bottleneck,
> unless you have something wrong in the client implementation.
>
> > >             sock = socket.create_connection((self.host, self.port),
> > > self.timeout)
> > >             sock2 = ssl.wrap_socket(sock, self.key_file,
> > > self.cert_file)
> > >             self.sock = CBSocket(sock2)
>
> What is CBSocket? What happens if you just write:
>     self.sock = sock2
>

Server's java process is taking 15% cpu.

Well, CBSocket is socket implementation that calls my callback on
data.
Both my classes AsyncHTTPSConnection and AsyncHTTPConnection use it
and use it the same way ( self.sock = CBSocket(sock2) ).
The implemetation of AsyncHTTPConnection differs from
AsyncHTTPSConnection only in connect method: sock2 =
ssl.wrap_socket(sock, self.key_file, self.cert_file)

class CBSocket(asynchat.async_chat):
""" This is a class that calls the callback when it has data and
it read it."""
def __init__(self, socket):
asynchat.async_chat.__init__(self, socket)

self._in_buffer = io.BytesIO()
self._closed = False
self._cb = None

def handle_read(self):
try:
read = self.socket.recv(65536)
except:
read = 0
raise
if not read and not self._closed:
self.handle_close()
self.close()
self._closed = True
return

self._in_buffer.write(read)

def sendall(self, data):
self.send(data)

def makefile(self, mode, buffsize= 8192):
self._in_buffer.seek(0)
return self._in_buffer

def set_cb(self, cb):
self._cb = cb
if self._closed:
   self._cb()
else:
   pass


def handle_close(self):
if self._cb:
self._cb()
self._closed = True
self.close()
del self._in_buffer

> > > > Also, there's a feature request to reduce overhead of SSL
> > > > connections, but it needs implementing:http://bugs.python.org/issue8106
>
> > > Well good to know this. Do we have any date when this will be
> > > available? I feel like contributing to this but kind of over occupied
> > > with several activities right now.
>
> Probably not in Python 3.2 anyway. But given your client isn't at 100%
> CPU when you launch your HTTPS test, it might not make a lot of
> difference.
>
> Regards
>
> Antoine.

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


Re: Tkinter: Exception RuntimeError: 'maximum recursion depth exceeded'

2010-10-13 Thread Olaf Dietrich
Lawrence D'Oliveiro :
> In message , Olaf Dietrich wrote:
> 
>> If I replace update() by update_idletasks(), the problem
>> disappears, but unfortunately, considerably fewer events
>> are recorded on the canvas (when connecting the pixels with
>> lines, the lines become much longer with update_idletasks()
>> than with update()).
[...]
> How about simply avoiding recursive updates.
> 
> Add this line to your __init__ method:
> 
>self.reentered = False
[...]
>if not save_reentered:
>self.root.update()

I tried this, but it makes the GUI even less responsive
than the unconditional call of update_idletasks().

Thanks,
Olaf

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


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Tim Bradshaw

On 2010-10-13 13:21:29 +0100, BartC said:

My money would have been on 0.25, based on using 1.0 for a 360° 
circular angle. It seems far more attractive than using the 
arbitrary-looking 6.28...


It may look arbitrary, but it isn't: it's about as non-arbitrary as it 
is possible to be.


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


Write Python Book - Packt Publishing.

2010-10-13 Thread Kshipra Singh
Hi All, 

I represent Packt Publishing, the publishers of computer related books. 

We are planning to publish a new book on improving the performance of Python 
applications and are currently looking out for potential authors to write it. 
You do not need to have any past writing experience. All that we need from our 
authors is a good knowledge of their subject, a passion to share it with others 
and ability to communicate clearly in English. We pay a royalty of 16% and an 
advance against it. 

If you find it interesting to write this book, please send me some details 
about your experience with the subject and your past writing experience (if you 
have any). 

Regards
Kshipra Singh
Author Relationship Manager
Packt Publishing
www.PacktPub.com
 
Skype: kshiprasingh15
Twitter: http://twitter.com/kshipras
 
Interested in becoming an author? Visit http://authors.packtpub.com for all the 
information you need about writing for Packt.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: optparser: how to register callback to display binary's help

2010-10-13 Thread Jean-Michel Pichavant

hiral wrote:

Hi,

I want to display help message of python script and then display help
message from the binary file (which also supports -h option):

Assumptions:
1) 'mybinary' - is linux executable file which supports '-h' and on '-
h' option it displays the help message
2) myscript.py - when passing '-h' option want to call 'mybinary -h'
and display help messages of both script and binary.

Code:

from optparse import OptionParser
[...]
parser = OptionParser()
parser.add_option("-e", "--execute", dest="file",
  help="Execute binary", metavar="FILE")
(options, args) = parser.parse_args()
if options.file:
subprocess.call(options.file)


Requirement:
$ python myscript.py -h



Thank you in advance.
-Hiral
  


Hi,

Try something like

def myHelp(option, opt, value, parser):
   parser.print_help()
   if hasattr(parser.values, 'file') and parser.values.file:
   proc = subprocess.Popen([parser.values.file, '-h'], 
stdout=subprocess.PIPE, stderr=subprocess.PIPE)

   print proc.stdout.read()
   print proc.stderr.read()

parser.remove_option('-h')
parser.add_option("-h", "--help",
 help="display the help message", action='callback', 
callback = myHelp)



Jean-Michel

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


Re: Performance evaluation of HTTPS library

2010-10-13 Thread Antoine Pitrou
On Wed, 13 Oct 2010 05:27:29 -0700 (PDT)
Ashish  wrote:
> 
> Well, CBSocket is socket implementation that calls my callback on
> data.
> Both my classes AsyncHTTPSConnection and AsyncHTTPConnection use it
> and use it the same way ( self.sock = CBSocket(sock2) ).
> The implemetation of AsyncHTTPConnection differs from
> AsyncHTTPSConnection only in connect method: sock2 =
> ssl.wrap_socket(sock, self.key_file, self.cert_file)
> 
> class CBSocket(asynchat.async_chat):
[...]

Ok, this won't work as expected. The first issue is that
ssl.wrap_socket() is a blocking operation, where your client will send
data and wait for the server reply (it's the SSL's handshake),
*before* the socket has been set in non-blocking mode by asyncore. It
means that your client will remain idle a lot of time, and explains
that neither the client nor the server reach 100% CPU utilization.

The second issue is that combining SSL and asyncore is more complicated
than that; there are various situations to consider which your code
doesn't address. The stdlib right now doesn't provide SSL support for
asyncore (see http://bugs.python.org/issue10084 ), so you would have to
do it yourself. I don't think it's worth the trouble, and would
recommend switching your client to a simple thread-based approach,
where you handle each HTTP(S) connection in a separate thread and stick
to blocking I/O.

Regards

Antoine.


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


Re: PEP 249 (database api) -- executemany() with iterable?

2010-10-13 Thread J. Gerlach
Am 13.10.2010 14:26, schrieb Jon Clements:
> On 12 Oct, 20:21, "J. Gerlach"  wrote:
>> Am 12.10.2010 17:10, schrieb Roy Smith:
>>
>>> [A]re there any plans to update the api to allow an iterable instead of
>>> a sequence?
>>
>> [sqlite3 example snipped]
> 
> What happens if you do itertools.repeat(0) instead of xrange(100) ?

And there I see why I don't want ``executemany()`` to take a generator
-- the never-ending ones will do some damage.

But on a similar note: would a ``execute_n_repeats(statement, iterable,
maximum_rows)`` be better?


Jörg

--
Have a nice day!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 249 (database api) -- executemany() with iterable?

2010-10-13 Thread Steven D'Aprano
On Wed, 13 Oct 2010 14:01:39 +1300, Lawrence D'Oliveiro wrote:

> In message <4cb4ba4e$0$1641$742ec...@news.sonic.net>, John Nagle wrote:
> 
>> In general, if you find yourself making millions of SQL database
>> requests in a loop, you're doing it wrong.
> 
> I’ve done this. Not millions, but certainly on the order of tens of
> thousands.

"I've done it" doesn't disprove that it is the wrong thing to do. It may 
simply mean that you too are doing it wrong.

I have no opinion either way, I'm just saying.



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


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Steven D'Aprano
Hmmm, my ISP's news software really doesn't like it when I cross-post to 
more than three newsgroups. So, trying again without comp.lang.c.

On Wed, 13 Oct 2010 02:00:46 +0100, BartC wrote:

> "RG"  wrote in message
> news:rnospamon-20651e.17410012102...@news.albasani.net...
>> In article , "BartC"
>>  wrote:
>>
>>> "Thomas A. Russ"  wrote in message
> 
>>> > But radians are dimensionless.
>>>
>>> But they are still units
>>
>> No, they aren't.
>>
>>> so that you can choose to use radians, degrees or gradians
>>
>> Those aren't units either, any more than a percentage is a unit.  They
>> are just different ways of writing numbers.
>>
>> All of the following are the same number written in different
>> notations:
>>
>> 0.5
>> 1/2
>> 50%
>>
>> Likewise, all of the following are the same number written in different
>> notations:
>>
>> pi/2
>> pi/2 radians
>> 90 degrees
>> 100 gradians
>> 1/4 circle
>> 0.25 circle
>> 25% of a circle
>> 25% of 2pi
>>
>> See?
> 
> But what exactly *is* this number? Is it 0.25, 1.57 or 90?

That's the wrong question. It's like asking, what exactly "is" the number
twenty-one -- is it "one and twenty", or 21, or 0x15, or 0o25, or 21.0, or
20.999... recurring, or 63/3, or XXI, or 0b10101, or "vinet et un", or any
one of many other representations.

Whether you say "two tens plus one unit" or "two to the power of four plus
two to the power of two plus two to the power of zero", the number is the
same number. So long as you use a consistent notation, the results you get
is independent of the notation. (Of course, some notations are more
convenient than others.)

Likewise, it doesn't matter whether you write 45° or π/4 radians, the
angle you are describing -- the number -- is the same. It turns out that
trigonometric functions have very nice (= important, useful) mathematical
properties if the notation we use for angles is the radian measure, where
2π radians make a full circle. This leads some people to mistakenly say
that radians are more fundamental than degrees, or that they are the
"actual" value for the angle.

But that's like saying that binary is the "actual" base for numbers
because addition and subtraction in binary have the nice property that
they're easy to implement in electrical circuits. Well, yes, and those
properties are very important, and mathematicians have done the sensible
thing to declare radians to be "the" mathematical measure of angles, but 
triangles will still be triangles regardless of whether we represent the 
angles using base ten radians or balanced ternary rational fractions. No 
matter what language we use to represent a number, the properties of the 
number remain the same. Or to put it another way, a rose by any other 
name would smell just the same.


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


Re: "Strong typing vs. strong testing" [OT]

2010-10-13 Thread Steven D'Aprano
On Tue, 12 Oct 2010 22:13:26 -0700, RG wrote:

>> The formula: circumference = 2 x pi x radius is taught in primary
>> schools, yet it's actually a very difficult formula to prove!
> 
> What's to prove?  That's the definition of pi.

Incorrect -- it's not necessarily so that the ratio of the circumference 
to the radius of a circle is always the same number. It could have turned 
out that different circles had different ratios. 

In fact, in the real world, this *is* the case -- as space-time is not 
flat except far away from any gravitational mass, classical geometry is 
only approximately valid for real circles.

Even in mathematics, there are spherical and hyperbolic geometries that 
doesn't assume that the angles in a triangle add to 180 degrees, or 
another way of putting it, that the ratio of circumference to radius is 
not necessarily pi.

http://mathforum.org/library/drmath/view/55021.html


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


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Arnaud Delobelle
Tim Bradshaw  writes:

> On 2010-10-13 13:21:29 +0100, BartC said:
>
>> My money would have been on 0.25, based on using 1.0 for a 360°
>> circular angle. It seems far more attractive than using the
>> arbitrary-looking 6.28...
>
> It may look arbitrary, but it isn't: it's about as non-arbitrary as it
> is possible to be.

Consider a few formulae that kids learn at school.

In radians, given an angle θ in a circle of radius r: 

* length of arc = rθ
* area of sector = 1/2 r²θ
* d/dx(sin x) = cos x
* d/dx(cos x) = -sinx x

Let's use 1 for the angle 2π.  Then:

* length of arc = 2πrθ
* area of sector = πr²θ
* d/dx(sin x) = 2πcos x
* d/dx(cos x) = 2πsin x

We've removed one π, but now π crops up in every formula!

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


send command to parent shell

2010-10-13 Thread Martin Landa
Hi,

is there a way how to send command from python script to the shell
(known id) from which the python script has been called? More
precisely, the goal is to exit running bash (on Linux) or cmd (on
Windows) directly from wxPython application, currently user needs to
quit wxPython application and then underlaying command prompt by
'exit' command.

Thanks in advance, Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


can I use more than one status condition name in imaplib.status()

2010-10-13 Thread harryos
Hi

In the signature of  of imaplib.status() method
MAP4.status(mailbox, names)
why is the 'names ' argument plural?Can I pass more than one name to
the method?
I can get correct  result when I call,
imapclient.status('Inbox', "(UNSEEN)")
or
imapclient.status('Inbox', "(RECENT)")

Is it possible to pass both these names ?
I tried,
imapclient.status('Inbox', "(UNSEEN,RECENT)")
which thows imaplib.error: STATUS command error: BAD ['Invalid
Command']

Any suggestions most welcome
harry
-- 
http://mail.python.org/mailman/listinfo/python-list


CherryPyWSGIServer multi-threading

2010-10-13 Thread Bart Ogryczak
I'm trying to create multi-threaded WSGI server. But somehow I'm
getting single threaded. What am I doing wrong?

#start myapp.py
from cherrypy.wsgiserver import CherryPyWSGIServer

def my_app(environ, start_response):
print "my_app"
import time
for i in range(10):
print i
time.sleep(1)
return ""

if __name__ == '__main__':
httpd = CherryPyWSGIServer(('0.0.0.0', 8000), my_app, numt)
print "Serving on port 8000..."
httpd.start()

#end myapp.py

I make 2 parallel request to my server and in the logs I see they are
run sequentially, not concurrently:

Serving on port 8000...
my_app
0
1
2
3
4
5
6
7
8
9
my_app
0
1
2
3
4
5
6
7
8
9
-- 
http://mail.python.org/mailman/listinfo/python-list


CherryPyWSGIServer multi-threading

2010-10-13 Thread Bart Ogryczak
I'm trying to create multi-threaded WSGI server. But somehow I'm
getting single threaded. What am I doing wrong?

#start myapp.py
from cherrypy.wsgiserver import CherryPyWSGIServer
def my_app(environ, start_response):
print "my_app"
import time
for i in range(10):
print i
time.sleep(1)
return ""
if __name__ == '__main__':
httpd = CherryPyWSGIServer(('0.0.0.0', 8000), sikuliSlave_app,
numthreads=10)
print "Serving on port 8000..."
httpd.start()
#end myapp.py
I make 2 parallel request to my server and in the logs I see they are
run sequentially, not concurrently:
Serving on port 8000...
my_app
0
1
2
3
4
5
6
7
8
9
my_app
0
1
2
3
4
5
6
7
8
9
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Write Python Book - Packt Publishing.

2010-10-13 Thread Sudheer Satyanarayana

Hello,

Apologies for spamming the list.

I didn't realize the publisher sent the email to the list. I thought it 
was a private email and replied to it instantly.



--
With warm regards,
Sudheer. S
Personal home page - http://sudheer.net | Tech Chorus - 
http://techchorus.net

Web and IT services - http://binaryvibes.co.in
--
http://mail.python.org/mailman/listinfo/python-list


Re: Write Python Book - Packt Publishing.

2010-10-13 Thread Sudheer Satyanarayana


We are planning to publish a new book on improving the performance of 
Python applications and are currently looking out for potential 
authors to write it. You do not need to have any past writing 
experience. All that we need from our authors is a good knowledge of 
their subject, a passion to share it with others and ability to 
communicate clearly in English. We pay a royalty of 16% and an advance 
against it.
If you find it interesting to write this book, please send me some 
details about your experience with the subject and your past writing 
experience (if you have any).

Hi Kshipra Singh,

Thanks for your email.

Unfortunately, I'm not interesting in writing about the topic you mention.

But I'm interested in writing about
1. Web scraping using Python
2. XML development using Python
3. XML development using PHP
4. Web scraping using PHP
5. Building and consuming web services using Python
6. Building and consuming web services using PHP

Let me know if you're interested in the topics above.

--

Sudheer Satyanarayana
Binary Vibes Information Technologies Pvt. Ltd.
Postal Address: #506, 10th B Main Road, I Block, Jayanagar, Bangalore -- 560 011
URL : www.binaryvibes.co.in
Phone: +91 80 41558451 * Mobile: +91 99005 07499
Community : http://techchorus.net

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


Re: "Strong typing vs. strong testing" [OT]

2010-10-13 Thread Tim Bradshaw

On 2010-10-13 14:20:30 +0100, Steven D'Aprano said:


ncorrect -- it's not necessarily so that the ratio of the circumference
to the radius of a circle is always the same number. It could have turned
out that different circles had different ratios.


But pi is much more basic than that, I think.  My background is in 
physics so I tend to do things from the geometrical point of view - and 
obviously you are correct that there are non-euclidean geometries.  But 
pi crops up, for instance, when dealing with complex numbers (e^(i pi) 
= -1 is the poster-child formula for this), and there are all sorts of 
series expressions for pi which have no really obvious geometrical 
interpretation.


(Of course, my view of the pi-in-complex-numbers is that this is 
because complex numbers turn out to essentially //be// two-dimensional 
euclidean geometry, but that's mostly because I want eerything to be 
geometry I think. In any case, I think you can get to pi being 
important in the same sort of way that you can get to e being 
important.)


(And, it sounds in the above like I think you might not know that pi 
crops up in complex numbers: that's just clumsy wording, sorry).


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


Re: "Strong typing vs. strong testing" [OT]

2010-10-13 Thread Antoon Pardon
On Wed, Oct 13, 2010 at 01:20:30PM +, Steven D'Aprano wrote:
> On Tue, 12 Oct 2010 22:13:26 -0700, RG wrote:
> 
> >> The formula: circumference = 2 x pi x radius is taught in primary
> >> schools, yet it's actually a very difficult formula to prove!
> > 
> > What's to prove?  That's the definition of pi.
> 
> Incorrect -- it's not necessarily so that the ratio of the circumference 
> to the radius of a circle is always the same number. It could have turned 
> out that different circles had different ratios. 

If that is your concern, you should have reacted to the previous poster
since in that case his equation couldn't be proven either.

Since by not reacting to the previous poster, you implicitely accepted
the equation and thus the context in which it is true: euclidean geometry.
So I don't think that concerns that fall outside this context have any
relevance.

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


Re: send command to parent shell

2010-10-13 Thread Nobody
On Wed, 13 Oct 2010 06:30:15 -0700, Martin Landa wrote:

> is there a way how to send command from python script to the shell
> (known id) from which the python script has been called?

For Unix, this should work, but in general it's the wrong thing to do:

import os
import signal
os.kill(os.getppid(), signal.SIGKILL)

This is a rather unfriendly way to kill the shell (it won't be able to
save its history, etc), and if the program was started from something
other than a shell, you might kill something you don't want to.

Using SIGHUP is more friendly and will probably work, but it could be
caught and/or ignored (for bash, SIGTERM, SIGQUIT and SIGINT /will/ be
ignored). If the shell can catch the signal in order to save its history,
it can catch it and ignore it.

There isn't a nice way to do it. There isn't supposed to be a nice way to
do it. Processes may control their children, but a child isn't supposed to
control its parent.

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


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Steve Schafer
On Wed, 13 Oct 2010 06:05:27 -0500, r...@rpw3.org (Rob Warnock) wrote:

>Why should it?!? If you look way under the covers, I suspect that even
>the "c^2" in "E = mc^2" is a "collected" term in the above sense [that is,
>if I recall my classes in introductory special relativity correctly].

In special relativistic terms, -c^2 is basically a unit-of-measurement
conversion factor between two values that represent the same underlying
"thing," analogous to the way that 25.4 is a conversion factor between
inches and millimetres. Whether you consider this equivalence to be an
intrinsic characteristic of the physical universe or merely a
consequence of the mathematics we use to describe the universe is a
philosophical question. But the fact that such an equivalence exists at
all suggests that the notion of "squaring time" as an analog of squaring
distance isn't really all that farfetched. (However, like the previous
poster, I've never been able to make any sense of it.)

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


Re: Tkinter: Exception RuntimeError: 'maximum recursion depth exceeded'

2010-10-13 Thread Jeff Hobbs
On Oct 13, 2:18 am, o...@dtrx.de (Olaf Dietrich) wrote:
> Jeff  Hobbs :
>
>
>
>
>
> > On Oct 12, 9:43 am, o...@dtrx.de (Olaf Dietrich) wrote:
>
> >> After some somewhat heavy mouse action inside the
> >> canvas (with the left button pressed), the application throws:
>
> >> | Exception RuntimeError: 'maximum recursion depth exceeded' in  >> method PhotoImage.__del__ of > 
> >> ignored
> >> | Exception in Tkinter callback
> [...]
> >> (and similiar ones)
>
> >> This error can be provoked faster by setting the recursion limit
> >> to lower values (e.g. 400 as in the comment above).
>
> >> Is there anything I can do (apart from increasing the recursion
> >> limit) to avoid this exception? Can I improve anything in the
> >> script above to make the whole thing more robust?
>
> > It seems very heavy-handed to create 1-pixel images for drawing onto
> > the canvas.  Any reason not to use something lighter weight?
>
> The example was _heavily_ simplified; originally, there was
> a background (e.g. gray-scale) image and I was drawing lines or
> other shapes onto that background that should appear in color
> and semi-transparent on top of the background. Additionally,
> both background and foreground can be zoomed and scrolled, and
> there should be a pixel-by-pixel correspondence between the
> (zoomed) background pixels and the semi-transparent shapes
> in the foreground (as opposed to overlayed vector graphics).
> I could not find a more light-weight solution for these
> requirements.

Interesting.  The canvas would support many of your primitives,
although the semi-transparent is only directly supported by images in
the core.  I'm not sure I entirely understand your app needs, but this
sounds like something the tkpath Tk extension solves (sort of canvas+
+), though that doesn't have a Tkinter wrapper that I'm aware of.

> > I suspect the "self.root.update()" is the problem.  Try
> > update_idletasks() instead, or to even avoid it if possible.  You
> > don't want to call update in the event loop, because you are likely
> > reprocessing from the same call, causing the recursion.
>
> Indeed, Tk/Toplevel/Canvas.update() seems to be at the
> center of the problem.
>
> If I replace update() by update_idletasks(), the problem
> disappears, but unfortunately, considerably fewer events
> are recorded on the canvas (when connecting the pixels with
> lines, the lines become much longer with update_idletasks()
> than with update()). If I remove both update() and
> update_idletasks(), things work similarly as with
> update_idletasks() (the display is only marginally slower
> than with update_idletasks()).
>
> I wonder if there is any compromise between update()
> and update_idletasks():
>
> * update(): smooth lines but recursion exception
> * update_idletasks(): non-smooth lines without exceptions

In general it isn't necessary to use update to keep up in pure Tcl/
Tk.  You can see an example drawing app at http://wiki.tcl.tk/15386
that has no trouble keeping up with the fastest mouse, without
update.  Without digging deeper into the Tkinter wrapper, maybe just
extending the recursionlimit is the easiest work-around?

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


Re: Using csv.DictReader with \r\n in the middle of fields

2010-10-13 Thread Neil Cerutti
On 2010-10-13, pstatham  wrote:
> Hopefully this will interest some, I have a csv file (can be
> downloaded from http://www.paulstathamphotography.co.uk/45.txt) which
> has five fields separated by ~ delimiters. To read this I've been
> using a csv.DictReader which works in 99% of the cases. Occasionally
> however the description field has errant \r\n characters in the middle
> of the record. This causes the reader to assume it's a new record and
> try to read it.

Here's an alternative idea. Working with csv module for this job
is too difficult for me. ;)

import re

record_re = 
"(?P.*?)~(?P.*?)~(?P.*?)~(?P.*?)~(?P.*?)\n(.*)"

def parse_file(fname):
with open(fname) as f:
data = f.read()
m = re.match(record_re, data, flags=re.M | re.S)
while m:
yield m.groupdict()
m = re.match(record_re, m.group(6), flags=re.M | re.S)

for record in parse_file('45.txt'):
print(record)

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


Re: Compiling as 32bit on MacOSX

2010-10-13 Thread Philip Semanchuk

On Oct 13, 2010, at 3:54 AM, Gregory Ewing wrote:

> Philip Semanchuk wrote:
> 
>> Hi Greg,
>> Are you talking about compiling Python itself or extensions?
> 
> I've managed to get Python itself compiled as 32 bit,
> and that also seems to take care of extensions built
> using 'python setup.py ...'.
> 
> I'm mainly concerned about non-Python libraries that
> get wrapped by the extensions, of which I've built up
> quite a collection over the years. Currently I'm having
> to keep a careful eye out when building them to make
> sure they don't get compiled with the wrong architecture,
> since gcc's natural inclination is to default to 64 bit
> whenever it's available.
> 
> So I was wondering if there was some way of globally
> changing that default that doesn't rely on compiler
> options getting passed correctly through the many and
> varied layers of build technology that one comes across.
> But from what I've seen so far, it seems not.

If CFLAGS isn't doing the trick for you, then I don't know what to suggest. 
Maybe some libs also need LDFLAGS='-arch i386 -arch x86_64'?

FYI, the `file` command will give you information about whether or not a binary 
is 32-bit, 64-bit or both.

$ file shlib/libreadline.6.1.dylib 
shlib/libreadline.6.1.dylib: Mach-O universal binary with 2 architectures
shlib/libreadline.6.1.dylib (for architecture i386):Mach-O dynamically 
linked shared library i386
shlib/libreadline.6.1.dylib (for architecture x86_64):  Mach-O 64-bit 
dynamically linked shared library x86_64


Good luck
Philip
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Keith Thompson
RG  writes:
> In article <8hl2ucfdv...@mid.individual.net>,
>  Gregory Ewing  wrote:
>> Tim Bradshaw wrote:
>> > In general any function 
>> > which raises its argument to more than one power ...  doesn't make
>> > much sense if its argument has units.
>> 
>> That's not true. Consider the distance travelled by a
>> falling object: y(t) = y0 + v0*t + 0.5*a*t**2. Here t has
>> dimensions of time, and it's being raised to different
>> powers in different terms. It works because the
>> coefficents have dimensions too, and all the terms end up
>> having the same dimensions.
>
> This reminds me of back when I was a kid and my dad was trying to teach 
> me basic physics.  He kept saying that the acceleration of gravity was 
> 9.8 meters per second squared and I just couldn't wrap my brain around 
> what it meant to square a second.
>
> Now that I think about it, I still can't.  :-)

Fuel economy can be measured in reciprocal acres (or reciprocal
hectares if you prefer).

miles/gallon or km/liter is distance / distance**3 --> distance**-2.

-- 
Keith Thompson (The_Other_Keith) ks...@mib.org  
Nokia
"We must do something.  This is something.  Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Pascal J. Bourguignon
Steven D'Aprano  writes:

> Hmmm, my ISP's news software really doesn't like it when I cross-post to
> more than three newsgroups. So, trying again without comp.lang.c.
>
> On Wed, 13 Oct 2010 02:00:46 +0100, BartC wrote:
>
>> "RG"  wrote in message
>> news:rnospamon-20651e.17410012102...@news.albasani.net...
>>> In article , "BartC"
>>>  wrote:
>>>
 "Thomas A. Russ"  wrote in message
>>
 > But radians are dimensionless.

 But they are still units
>>>
>>> No, they aren't.
>>>
 so that you can choose to use radians, degrees or gradians
>>>
>>> Those aren't units either, any more than a percentage is a unit.  They
>>> are just different ways of writing numbers.
>>>
>>> All of the following are the same number written in different
>>> notations:
>>>
>>> 0.5
>>> 1/2
>>> 50%
>>>
>>> Likewise, all of the following are the same number written in different
>>> notations:
>>>
>>> pi/2
>>> pi/2 radians
>>> 90 degrees
>>> 100 gradians
>>> 1/4 circle
>>> 0.25 circle
>>> 25% of a circle
>>> 25% of 2pi
>>>
>>> See?
>>
>> But what exactly *is* this number? Is it 0.25, 1.57 or 90?
>
> That's the wrong question. It's like asking, what exactly "is" the number
> twenty-one -- is it "one and twenty", or 21, or 0x15, or 0o25, or 21.0, or
> 20.999... recurring, or 63/3, or XXI, or 0b10101, or "vinet et un", or any
> one of many other representations.

This is not the wrong question.  These are two different things.

In the case of 0.25, 1.57 or 90, you have elements of the same set of
real numbers ℝ, which are used to represent the same entity, which IS NOT
a number, but an angle.  Angles are not in the ℝ set, but in ℝ/2π, which
is an entirely different set with entirely different properties.



In the other case, we have strings "21", "0x15", "0o25", "21.0",
"20.999...", "63/3", "XXI", "0b10101", "vingt et un", that represent the
same number in ℝ.




So you have different pairs of sets and different representationnal
mapping.  There's very little in common between an angle of 90 degree,
and the number 21.




> Likewise, it doesn't matter whether you write 45° or π/4 radians, the
> angle you are describing -- the number -- is the same.

No.  The numbers ARE different.  One number is 45, the other is π/4.
What is the same, is the angle that is represented.

I cannot fathom how you can arrive at such a misunderstanding.  It's
rather easy to picture out:

ℝ   .ℝ/2π..
   :  : ::
  ::degree : full turn:
  :45 --\ :
  : :  : \:
  : :  :   angle of an eighth of a turn   :
  : :radian: /:
  :π/4 -/ :
  : :  :quarter turn  :
   :   :::
...  


--
__Pascal Bourguignon__ http://www.informatimago.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


how do I search python mailing list archives?

2010-10-13 Thread Sean Choi
What are the various ways to search the python mailing list archives?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Seebs
On 2010-10-12, Jonas H.  wrote:
> Just a few pointers, looks quite good to me for a newbie :)

Thanks!

> * Less action in __init__.

I'm a bit curious about this.  The __init__ functions in this are, at
least for now, pretty much doing only what's needed to create the objects
from their inputs.

> * Use `open` instead of `file` to open a file

Done.

> * Have a look at context managers for file handling (avoids doing 
> error-prune stuff like __del__)

Okay.  I wasn't at all sure the __del__ was needed.

> * Your `del` in line 464 is useless. A reference will be removed from 
> the object bound to the local variable 'source' anyway because of the 
> re-assignment.

Oh.  D'oh.  You can see the C programmer instinct there; that was the
sort of thing that would, in C, be:
for (i = 0; i < n; ++i)
free(array[i]);

But of course, that doesn't work.  I guess that leads to a general question:
Is it safe for me to assume that all my files will have been flushed and
closed?  I'd normally assume this, but I seem to recall that not every
language makes those guarantees.

> * according to common Python style guides you should not use underscores 
> in class names.

Makes sense.  I was finding "CArgument" hard to read, and couldn't think
of a better name.

> * no need for 'r' in `open` calls ('r' is the default mode)

'k.

> * `line == ''` can be written more pythonic as `not line`

'k.

> * `str.{r,l,}strip` removes '\n\t\r ' by default, no need for an 
> argument here (line 440 for example)

Ahh, good to know.

> * you might want to pre-compile regular expressions (`re.compile`)

Thought about it, but decided that it was probably more complexity than I
need -- this is not a performance-critical thing.  And even if it were, well,
I'm pretty sure it's I/O bound.  (And on my netbook, the time to run this
is under .2 seconds in Python, compared to 15 seconds in shell, so...)

> * raising `Exception` rather than a subclass of it is uncommon.

Okay.  I did that as a quick fix when, finally having hit one of them,
I found out that 'raise "Error message"' didn't work.  :)  I'm a bit unsure
as to how to pick the right subclass, though.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Seebs
On 2010-10-12, Chris Rebert  wrote:
> 2.
> self.f = file(path, 'r')
> if not self.f:
> return None
>
> The "if" here is pointless; I'm reasonably sure files are always
> considered boolean true.

I actually seem to have done this wrong anyway -- I was thinking in
terms of the C-like idiom of returning NULL when a constructor-like thing
fails.  This ought to have been a raise of some sort to prevent the caller
from getting an object that didn't work out.

> Python's grammar has "not in" as an "operator" for just such occasions ==>

Ahh!

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Seebs
On 2010-10-12, MRAB  wrote:
> The code does require Python 2 and the use of except ... as ... requires 
> at least version 2.6.

Whoops.

> Line 51

> The __init__ method should always return None. There's no need to be 
> explicit about it, just use a plain "return".

The real issue here is that I was assuming that open('nonexistent') returned
None rather than raising an exception.

> The error message says:

>  "Couldn't open %s to read a template."

> but it's opening the file for writing.

Ahh, my famed attention to detail strikes again. :)

> You can't really rely on the destructor __del__ being called.

Interesting.  Do I just rely on files getting closed?

> Line 333

> Shouldn't you be checking that the name of the attribute you're setting 
> doesn't clash with one of the existing attributes? Are you sure that a 
> dict wouldn't be a better idea?

Actually, not sure at all.  There's a sort of gradual evolution going on
here, in that I was trying to avoid having a separate dict that I had to
populate with a bunch of stuff -- thus the switch to a hand-written
__getitem__.  What I probably ought to do/have done is use a dict first,
and set things in the dict from here, then check the dict first, then
regular getattr, and so on.

> Line 447
>
> The form:
>
>  except ... as ...
>
> is in Python versions >= 2.6, but not earlier.

Oops.  Is there a way to interact with the caught exception in earlier
Python?

> This use of del just deletes the name from the namespace and won't 
> necessarily call the __del__ method of the 'source' object. It's better 
> to rely on something more explicit like a 'close' method. (If you can't 
> be sure which version of Python it'll use then context managers are 
> probably out anyway!)

Okay, good to know.  I'll fix that.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Seebs
On 2010-10-12, Hallvard B Furuseth  wrote:
>> list = map(lambda x: x.call(), self.args)
>> return ', '.join(list)
>
>   return ', '.join([x.call() for x in self.args])

I think I wrote that before I found out about list comprehensions.  How
new are list comprehensions?

I do like that, it's clearer.

>> self.type, self.name = None, None

> Actually you can write self.type = self.name = None,
> though assignment statements are more limited than in C.
> (And I think they're assigned left-to-right.)

Okay.

>>  match = re.match('(.*)\(\*([a-zA-Z0-9_]*)\)\((.*)\)', text)

> Make a habit of using r'' for strings with lots of backslashes,
> like regexps.

Hmm.  There's an interesting question -- does this work as-is?  I'm
assuming it must or it would have blown up on me pretty badly, so
presumably those backslashes are getting passed through untouched
already.  But if that's just coincidence (they happen not to be valid
\-sequences), I should definitely fix that.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 249 (database api) -- executemany() with iterable?

2010-10-13 Thread John Nagle

On 10/12/2010 6:01 PM, Lawrence D'Oliveiro wrote:

In message<4cb4ba4e$0$1641$742ec...@news.sonic.net>, John Nagle wrote:


In general, if you find yourself making millions of
SQL database requests in a loop, you're doing it wrong.


I’ve done this. Not millions, but certainly on the order of tens of
thousands.


   It's a scaling issue.  Millions of INSERT or UPDATE requests can
take hours.  That's when you need the speedup of bulk loading.


  Big database loads are usually done by creating a text file
with the desired data, then using a LOAD DATA INFILE command.


May not always be flexible enough.


   True; you can't do anything with LOAD DATA INFILE but load data.
If you need selects or joins within inserts, you may have to do it
the long way.


This (in MySQL) is tens to hundreds of times faster than doing individual
INSERT or UPDATE commands.


Why should that be? The database cannot read a text file any faster than I
can.


Because the indices are updated in one big update, rather than
after each change to the database.

Also note that there are some issues with doing a huge volume of
updates in one MySQL InnoDB transaction.  The system has to keep the
data needed to undo the updates, and there's a limit on the amount of
pending transaction history that can be stored.

It's common to load data into a new, empty table, then, once
the reload has succeeded, do a RENAME like CURRENT->OLD, NEW->CURRENT.
Rename of multiple databases is atomic and interlocked with other
operations, so you can replace an entire table on a live server.

I have some bulk databases which are updated from external
sources.  The PhishTank database is updated with UPDATE statements
every three hours. But the Open Directory database is updated by
downloading a big gzipped file of XML, creating a new database
table, then renaming.  That load takes hours, once a week.

(All this applies to MySQL, and to some extent, Postgres.
If you're using SQLite, it's different.  But a million records
is big for SQLite, which is, after all, a "lite" database.
At 10,000 records, you don't have to worry about any of this
stuff.  At 1,000,000 records, you do.)

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


Re: Difficulty in easy_install

2010-10-13 Thread John Nagle

On 10/11/2010 1:45 AM, sankalp srivastava wrote:


  I am having difficulty in easy_installing
I use a proxy server and strange errors , like it can't fetch the
package is showing up .
the package is pyspeech ...please help me :(

I don't know if the proxy server is causing the problems , in linux i
would have import http-proxy in .bashrc
but am not a windows expert
can anyone help me plz


That's about typical.  "easy_install" isn't "easy".  It has some
built-in assumptions about where various files are stored, and if
the installation doesn't match them, installs fail with obscure
error messages.

"egg" files are really just "zip" files.  It's sometimes
necessary to unpack them, and run "python setup.py".

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


Re: My first Python program

2010-10-13 Thread Chris Rebert
On Wed, Oct 13, 2010 at 9:56 AM, Seebs  wrote:
> On 2010-10-12, MRAB  wrote:

>> Line 51
>
>> The __init__ method should always return None. There's no need to be
>> explicit about it, just use a plain "return".
>
> The real issue here is that I was assuming that open('nonexistent') returned
> None rather than raising an exception.

For future reference, the significant majority of things in Python
raise exceptions upon encountering errors rather than returning error
values of some sort.
Aside from APIs which explicitly provide a parameter to be returned as
a default value in case of error (e.g. getattr(obj, name, default)),
the only common exception* I can come up with off the top of my head
is str.find()**, and even that has an exception-throwing cousin,
str.index().

Cheers,
Chris
--
*No pun intended; I just didn't want to have to break out a thesaurus.
**Returns -1 rather than raising ValueError
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how do I search python mailing list archives?

2010-10-13 Thread Daniel Fetchinson
> What are the various ways to search the python mailing list archives?

If you are searching for 'foo' and 'bar' you can try this in google:

foo bar site:mail.python.org inurl:python-list

Cheers,
Daniel


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Ethan Furman

Seebs wrote:

On 2010-10-12, Hallvard B Furuseth  wrote:

>

self.type, self.name = None, None



Actually you can write self.type = self.name = None,
though assignment statements are more limited than in C.
(And I think they're assigned left-to-right.)


Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
--> a = 2
--> b = 7
--> c = 13
--> a = b = c = 'right to left'
--> a, b, c
('right to left', 'right to left', 'right to left')


 match = re.match('(.*)\(\*([a-zA-Z0-9_]*)\)\((.*)\)', text)



Make a habit of using r'' for strings with lots of backslashes,
like regexps.


Hmm.  There's an interesting question -- does this work as-is?  I'm
assuming it must or it would have blown up on me pretty badly, so
presumably those backslashes are getting passed through untouched
already.  But if that's just coincidence (they happen not to be valid
\-sequences), I should definitely fix that.


Unknown backslash sequences are passed through as-is.

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


Re: if the else short form

2010-10-13 Thread John Nagle

On 10/10/2010 6:46 PM, Lawrence D'Oliveiro wrote:


Languages that insisted on being able to do proper compiler-level cross
checks between separately-compiled modules (e.g. Modula-2, Ada) never really
became that popular. This saddened me.


   It's an sad consequence of a UNIX mindset that "you can't change
the linker".  This stems from the early days of UNIX, where the
linker was in assembler, very limited, and had very few
comments.  That's why C++ had "name mangling", instead of
a type-aware linker.  Really.

   There are interesting things to do at link time, and the Gnu
toolchain finally added some of them.  Weak links, for example -
ones which are resolved if the target is present, but won't
pull it in. This allows bringing in C++ classes without
hauling in every unreferenced member function of the class.

   Modula did more at link time.  In Modula, modules had
initialization sections.  Initialization sections could call
functions in other modules.   The rule was that you couldn't call
into a module until the module's initialization section had run.
Conveniently, the Modula "binder" computed the dependency graph
of what called what, and ordered the initialization sections so
that all modules were initialized before being called.  The
binder could detect dependency loops, and reported them at
link time.  So if the program would build, it would initialize
in proper order.

   This is a nice check, because it's a global property of
the program, not a local bug.  It's the sort of thing that
appears on large projects where different people are doing
different modules.  Computers are better than
people at finding that class of problem.

   C++ got this wrong, leading to the "static initialization
order fiasco".  Python is vulnerable to this problem in
import loops, although the consequences aren't as severe as
in C++.

John Nagle

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


Re: My first Python program

2010-10-13 Thread Jean-Michel Pichavant

Seebs wrote:

So, I'm new to Python, though I've got a bit of experience in a few other
languages.  My overall impressions are pretty mixed, but overall positive;
it's a reasonably expressive language which has a good mix between staying
out of my way and taking care of stuff I don't want to waste attention on.

My first project was to replace a shell script with a Python script.  The
context is a project ("pseudo") which does some really hairy stuff in C.
Part of what it does involves creating hundreds of stub functions.  The
existing shell script did this successfully, but wasn't particularly
fast, and was basically unmaintainable.  So I've redone it in Python.

The input is a list of C function declarations, such as:
int foo(char *s);
and the output is several files, which include lists of these functions,
declarations for wrappers for them, and so on.  So that would produce
something to the effect of:
int foo(char *s) {
   /* various magic */
   int rc = -1;
   /* stuff happens */
   rc = wrap_foo(s);
   /* more magic */
   return rc;
}

Where it gets complicated is that there are, of course, special cases;
for instance, the wrapper for 'int open(char *path, int mode, int flags)' has
to know that the flags argument is conditional, and not always provided, so
it declares open as "int open(char *path, int mode, ...)", then extracts
flags using a va_list.  Weird stuff ensues.  It's a pretty weird hunk of
code.

The source in its current form:

http://github.com/wrpseudo/pseudo/blob/master/makewrappers

The underlying task is fairly ugly, and it's my first Python project,
so the result isn't particularly pretty, but I'd be interested in
feedback on it.  However, I'm not at all sure whether it's appropriate for
this group to post 467 lines of code with no question beyond "how am
I screwing this up?"

At this point, it does everything I want it to do, so the question isn't
"how can I do this?", but "how should I have done this more idiomatically?"

There's a few quirks; one is that I have to run on whatever Python happens
to be installed on a variety of systems, from RHEL4 to Fedora 13 or so.
(It is, at least for now, completely unimportant whether I run on non-Linux
systems.)  I can't rely on packages or extensions which aren't going to
be in the base Python install.

Apart from that... I'm interested in feedback.  I'm not expecting that
this is good or idiomatic Python, but I'd like to learn to write Python
correctly and expressively, and there's nothing like criticism to improve
code.  And if people would prefer that I post the code here, I could,
I just figured that it was a bit large.

-s
  
If you plan to code in python, then you may consider using a linter. 
These a formidable tools to help you set your coding rules, and most of 
these tools can detect most of the basics errors, or coding wrong habits.


If you wonder about some defects reported by such linters, you can then 
ask in this list why something is not that good, because it may not be 
always obvious.


'pylint' is one them, pretty effective.

JM


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


Re: My first Python program

2010-10-13 Thread MRAB

On 13/10/2010 18:17, Chris Rebert wrote:

On Wed, Oct 13, 2010 at 9:56 AM, Seebs  wrote:

On 2010-10-12, MRAB  wrote:



Line 51



The __init__ method should always return None. There's no need to be
explicit about it, just use a plain "return".


The real issue here is that I was assuming that open('nonexistent') returned
None rather than raising an exception.


For future reference, the significant majority of things in Python
raise exceptions upon encountering errors rather than returning error
values of some sort.
Aside from APIs which explicitly provide a parameter to be returned as
a default value in case of error (e.g. getattr(obj, name, default)),
the only common exception* I can come up with off the top of my head
is str.find()**, and even that has an exception-throwing cousin,
str.index().

Cheers,
Chris
--
*No pun intended; I just didn't want to have to break out a thesaurus.
**Returns -1 rather than raising ValueError


The re.search and so forth return Match objects or None.
--
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Jonas H.

On 10/13/2010 06:48 PM, Seebs wrote:

Is it safe for me to assume that all my files will have been flushed and
closed?  I'd normally assume this, but I seem to recall that not every
language makes those guarantees.


Not really. Files will be closed when the garbage collector collects the 
file object, but you can't be sure the GC will run within the next N 
seconds/instructions or something like that. So you should *always* make 
sure to close files after using them. That's what context managers were 
introduced for.


with open('foobar') as fileobject:
do_something_with(fileobject)

basically is equivalent to (simplified!)

fileobject = open('foobar')
try:
do_something_with(fileobject)
finally:
fileobject.close()

So you can sure `fileobject.close()` is called in *any* case.


* you might want to pre-compile regular expressions (`re.compile`)


Thought about it, but decided that it was probably more complexity than I
need -- this is not a performance-critical thing.  And even if it were, well,
I'm pretty sure it's I/O bound.  (And on my netbook, the time to run this
is under .2 seconds in Python, compared to 15 seconds in shell, so...)


Forget about my suggestion. As someone pointed out in a another post, 
regular expressions are cached anyway.



I'm a bit unsure as to how to pick the right subclass, though.


There are a few pointers in the Python documentation on exceptions.

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


Re: how do I search python mailing list archives?

2010-10-13 Thread Ned Deily
In article 
,
 Daniel Fetchinson  wrote:
> > What are the various ways to search the python mailing list archives?
> 
> If you are searching for 'foo' and 'bar' you can try this in google:
> 
> foo bar site:mail.python.org inurl:python-list

The mailing list is also mirrored at gmane.org under the group name 
gmane.comp.python.general.  You can use gmane's Xapian-powered search 
engine here: http://search.gmane.org/

-- 
 Ned Deily,
 n...@acm.org

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


Re: My first Python program

2010-10-13 Thread Ian Kelly
On Wed, Oct 13, 2010 at 11:28 AM, Ethan Furman  wrote:

> Seebs wrote:
>
>> On 2010-10-12, Hallvard B Furuseth  wrote:
>>
> >
>
>>  self.type, self.name = None, None

>>>
>>  Actually you can write self.type = self.name = None,
>>> though assignment statements are more limited than in C.
>>> (And I think they're assigned left-to-right.)
>>>
>>
> Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> --> a = 2
> --> b = 7
> --> c = 13
> --> a = b = c = 'right to left'
> --> a, b, c
> ('right to left', 'right to left', 'right to left')
>

I'm not sure how that demonstrates anything, but here is an example where
the order of assignment actually matters:

>>> d['a'] = d = {}
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'd' is not defined
>>> d = d['a'] = {}
>>> d
{'a': {...}}

As you can see, they're assigned left-to-right.

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


Re: My first Python program

2010-10-13 Thread Chris Torek
In article 
Seebs   wrote:
>> * raising `Exception` rather than a subclass of it is uncommon.
>
>Okay.  I did that as a quick fix when, finally having hit one of them,
>I found out that 'raise "Error message"' didn't work.  :)  I'm a bit unsure
>as to how to pick the right subclass, though.

For exceptions, you have two choices:

  - pick some existing exception that seems to make sense, or
  - define your own.

The obvious cases for the former are things like ValueError or
IndexError.  Indeed, in many cases, you just let a work-step
raise these naturally:

def frobulate(self, x):
...
self.table[x] += ...   # raises IndexError when x out of range
...

For the latter, make a class that inherits from Exception.  In
a whole lot of cases a trivial/empty class suffices:

class SoLongAndThanksForAllTheFish(Exception):
pass

def ...:
...
if somecondition:
raise SoLongAndThanksForAllTheFish()

Since Exception provides a base __init__() function, you can
include a string:

raise SoLongAndThanksForAllTheFish('RIP DNA')

which becomes the .message field:

>>> x = SoLongAndThanksForAllTheFish('RIP DNA')
>>> x.message
'RIP DNA'
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)  http://web.torek.net/torek/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Chris Torek
In article 
Jonas H.  wrote:
>On 10/13/2010 06:48 PM, Seebs wrote:
>> Is it safe for me to assume that all my files will have been flushed and
>> closed?  I'd normally assume this, but I seem to recall that not every
>> language makes those guarantees.
>
>Not really. Files will be closed when the garbage collector collects the 
>file object, but you can't be sure the GC will run within the next N 
>seconds/instructions or something like that. So you should *always* make 
>sure to close files after using them. That's what context managers were 
>introduced for.
>
> with open('foobar') as fileobject:
> do_something_with(fileobject)
>
>basically is equivalent to (simplified!)
>
> fileobject = open('foobar')
> try:
> do_something_with(fileobject)
> finally:
> fileobject.close()
>
>So you can sure `fileobject.close()` is called in *any* case.

Unfortunately "with" is newish and this code currently has to
support python 2.3 (if not even older versions).
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)  http://web.torek.net/torek/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Seebs
On 2010-10-13, Chris Rebert  wrote:
> For future reference, the significant majority of things in Python
> raise exceptions upon encountering errors rather than returning error
> values of some sort.

Yes.  I'm getting used to that -- it's a bit of a shift, because I'm
used to exceptions being *exceptional* -- as in, not a failure mode
you would expect to see happening.  So for instance, I wouldn't expect
to get an exception for EOF, because that's not exceptional, that's
virtually guaranteed to happen whenever you interact with files.  I am
gonna have to retrain a bit.

> Aside from APIs which explicitly provide a parameter to be returned as
> a default value in case of error (e.g. getattr(obj, name, default)),
> the only common exception* I can come up with off the top of my head
> is str.find()**, and even that has an exception-throwing cousin,
> str.index().

Interesting!  That may take me some getting used to.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing" [OT]

2010-10-13 Thread Steven D'Aprano
On Wed, 13 Oct 2010 15:07:07 +0100, Tim Bradshaw wrote:

> On 2010-10-13 14:20:30 +0100, Steven D'Aprano said:
> 
>> ncorrect -- it's not necessarily so that the ratio of the circumference
>> to the radius of a circle is always the same number. It could have
>> turned out that different circles had different ratios.
> 
> But pi is much more basic than that, I think.

Well yes it is, but how did anyone *know* that it was? How did anyone 
even know that there was a constant pi = 3.1415... ? It's not like it was 
inscribed on the side of some mountain in letters of fire 100 ft high, 
and even if it were, why should we believe it?

The context of my comment was the statement that there is no need to 
prove that C = 2πr because that's the definition of pi. That may be how 
pi was first defined, but the Greeks didn't just *decide* that the ratio 
C/r was a constant, they discovered it. They constructed a pair of 
regular polygons with n sides, the circle inscribing one polygon and in 
turn being inscribed by the second, and observed that as n approached 
infinity two things happened: the inner and outer polygons both became 
infinitesimally close to the circle, and the ratio of the perimeter of 
either polygon to twice the radius approached the same constant.

By modern standards it wasn't *quite* vigorous -- the Greeks hadn't 
invented calculus and limits, and so had to do things the hard way -- but 
nevertheless it was an inspired proof. I call it a proof rather than a 
definition because, prior to this, nobody knew that there was such a 
number as pi, let alone what it's value was. 


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


Re: My first Python program

2010-10-13 Thread Seebs
On 2010-10-13, Jean-Michel Pichavant  wrote:
> If you wonder about some defects reported by such linters, you can then 
> ask in this list why something is not that good, because it may not be 
> always obvious.

> 'pylint' is one them, pretty effective.

Okay, several questions about stuff pylint found.

1.  If I have a message that I wish to print, it is quite possible
that message + indentation exceeds 80 lines.  What's the idiomatic way
to solve this?  Do I just break the string up into parts, or do I just
accept that some lines are over 80 characters, or what?
2.  It warns about **kw, both because the name is short and because of
the "** magic".  I was previously advised that the name "kw" is canonical
for that usage, in which case, why am I getting linted at?
3.  More generally, the usage of **kw is probably not really right, but I'm
not sure what to do.

The issue here is as follows:

In C, some functions have an optional argument with the curious trait that,
if present, it is always of the same type.  e.g., open(2).  In my wrappers,
I indicate this by declaring it as something like "...{mode_t mode}".  The
intent is that in a declaration, this will turn into:
foo(blah blah blah, ... /* mode_t mode */)
so there's an indication of why there's a "..." there.
But C comments don't nest.  And there's a couple of points where I want to
put the declaration in a comment.  So in those cases, I need to do something
other than /*...*/:
/* foo(blah blah blah, ... mode_t mode) */

The problem:  The determination of whether I wish to do this is at the level
of the "represent this function in the following way" (Function.comment()),
but the implementation is two layers down.  So right now, I am passing
down 'comment = True' from the top level through, and I'm doing it using
a **kw keyword argument.

The rationale is that I could just use
def decl(comment = False):
...
but then the invocation:
func.decl(True)
would be utterly opaque.  I want to name the thing I'm passing or otherwise
indicate what it is.

It could be that I am Doing This Wrong.  Is there a good idiom for labeling
optional arguments, and passing them on (if they exist)?

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Seebs
On 2010-10-13, Jonas H.  wrote:
> Not really. Files will be closed when the garbage collector collects the 
> file object, but you can't be sure the GC will run within the next N 
> seconds/instructions or something like that. So you should *always* make 
> sure to close files after using them. That's what context managers were 
> introduced for.

>  with open('foobar') as fileobject:
>  do_something_with(fileobject)

That makes sense.  I don't think it'd quite work in this case, because I
want to open several files all at once, do a ton of work that populates
them with files, and then close them all.

This is a nice idiom, though.  In C, I've been sort of missing that idiom,
which I first encountered in Ruby.  (I mean, spelled differently, but the
same basic thing.)

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Seebs
On 2010-10-13, Chris Torek  wrote:
> Unfortunately "with" is newish and this code currently has to
> support python 2.3 (if not even older versions).

I think it might be 2.4 and later.  I'm not sure.  Of course, this being
the real world, the chances that I'll be able to stick with "Python 2" and
not have to simultaneously also support Python 1 and Python 3 are probably
about 20%.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Chris Kaynor
On Wed, Oct 13, 2010 at 12:10 PM, Seebs  wrote:

> On 2010-10-13, Jean-Michel Pichavant  wrote:
> > If you wonder about some defects reported by such linters, you can then
> > ask in this list why something is not that good, because it may not be
> > always obvious.
>
> > 'pylint' is one them, pretty effective.
>
> Okay, several questions about stuff pylint found.
>
> 1.  If I have a message that I wish to print, it is quite possible
> that message + indentation exceeds 80 lines.  What's the idiomatic way
> to solve this?  Do I just break the string up into parts, or do I just
> accept that some lines are over 80 characters, or what?
> 2.  It warns about **kw, both because the name is short and because of
> the "** magic".  I was previously advised that the name "kw" is canonical
> for that usage, in which case, why am I getting linted at?
> 3.  More generally, the usage of **kw is probably not really right, but I'm
> not sure what to do.
>
> The issue here is as follows:
>
> In C, some functions have an optional argument with the curious trait that,
> if present, it is always of the same type.  e.g., open(2).  In my wrappers,
> I indicate this by declaring it as something like "...{mode_t mode}".  The
> intent is that in a declaration, this will turn into:
>foo(blah blah blah, ... /* mode_t mode */)
> so there's an indication of why there's a "..." there.
> But C comments don't nest.  And there's a couple of points where I want to
> put the declaration in a comment.  So in those cases, I need to do
> something
> other than /*...*/:
>/* foo(blah blah blah, ... mode_t mode) */
>
> The problem:  The determination of whether I wish to do this is at the
> level
> of the "represent this function in the following way" (Function.comment()),
> but the implementation is two layers down.  So right now, I am passing
> down 'comment = True' from the top level through, and I'm doing it using
> a **kw keyword argument.
>
> The rationale is that I could just use
>def decl(comment = False):
>...
> but then the invocation:
>func.decl(True)
> would be utterly opaque.  I want to name the thing I'm passing or otherwise
> indicate what it is.
>
> It could be that I am Doing This Wrong.  Is there a good idiom for labeling
> optional arguments, and passing them on (if they exist)?
>

You can always name the arguments (the following work in 2.5 and 2.6,
barring typos - the code is untested):

def func1(arg1, arg2):
print arg1, arg2

> func1(arg2=1, arg1=2)
2 1
> func1(2, arg2=1)
2 1

def func2(arg1, arg2, optionalArg=3):
print arg1, arg2, optionalArg

> func2(1, 2)
1 2 3
> func2(1, 2, optionalArg=4)
1 2 4
> func2(1, 2, 4)
1 2 4
> func2(arg2=1, arg1=2, optionalArg=4)
2 1 4

You can also mix and match:

def func1(arg1, arg2, arg3):
print arg1, arg2, arg3

> func1(1, arg3=2, arg2=3)
1 3 2



> -s
> --
> Copyright 2010, all wrongs reversed.  Peter Seebach /
> usenet-nos...@seebs.net
> http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
> http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
> I am not speaking for my employer, although they do rent some of my
> opinions.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Chris Kaynor
On Wed, Oct 13, 2010 at 12:13 PM, Seebs  wrote:

> On 2010-10-13, Chris Torek  wrote:
> > Unfortunately "with" is newish and this code currently has to
> > support python 2.3 (if not even older versions).
>
> I think it might be 2.4 and later.  I'm not sure.  Of course, this being
> the real world, the chances that I'll be able to stick with "Python 2" and
> not have to simultaneously also support Python 1 and Python 3 are probably
> about 20%.
>

I'm fairly sure the with statement was first added in 2.5. In 2.5, you need
to use "from __future__ import with_statement" to enable it - in 2.6 it is
always enabled (the future import is still allowed for backwards
compatibility, but it does nothing).


>
> -s
> --
> Copyright 2010, all wrongs reversed.  Peter Seebach /
> usenet-nos...@seebs.net
> http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
> http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
> I am not speaking for my employer, although they do rent some of my
> opinions.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Chris Kaynor
On Wed, Oct 13, 2010 at 12:12 PM, Seebs  wrote:

> On 2010-10-13, Jonas H.  wrote:
> > Not really. Files will be closed when the garbage collector collects the
> > file object, but you can't be sure the GC will run within the next N
> > seconds/instructions or something like that. So you should *always* make
> > sure to close files after using them. That's what context managers were
> > introduced for.
>
> >  with open('foobar') as fileobject:
> >  do_something_with(fileobject)
>
> That makes sense.  I don't think it'd quite work in this case, because I
> want to open several files all at once, do a ton of work that populates
> them with files, and then close them all.
>
> This is a nice idiom, though.  In C, I've been sort of missing that idiom,
> which I first encountered in Ruby.  (I mean, spelled differently, but the
> same basic thing.)
>

For opening multiple files, you can either nest the with statements:
with open('foobar1') as foobar1:
   dosomethingwithfoobar1()
   with open('foobar2') as foobar2:
  dosomethingwithfoobar2()
  dosomethingelsewithfoobar1()

or you can use the contextlib module to nest them in one line:
import contextlib
with contextlib.nested(open('foobar1'), open('foobar2')) as (foobar1,
foobar2):
dosomethingwithfoobar1and2()


> -s
> --
> Copyright 2010, all wrongs reversed.  Peter Seebach /
> usenet-nos...@seebs.net
> http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
> http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
> I am not speaking for my employer, although they do rent some of my
> opinions.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread MRAB

On 13/10/2010 20:03, Seebs wrote:

On 2010-10-13, Chris Rebert  wrote:

For future reference, the significant majority of things in Python
raise exceptions upon encountering errors rather than returning error
values of some sort.


Yes.  I'm getting used to that -- it's a bit of a shift, because I'm
used to exceptions being *exceptional* -- as in, not a failure mode
you would expect to see happening.  So for instance, I wouldn't expect
to get an exception for EOF, because that's not exceptional, that's
virtually guaranteed to happen whenever you interact with files.  I am
gonna have to retrain a bit.


Aside from APIs which explicitly provide a parameter to be returned as
a default value in case of error (e.g. getattr(obj, name, default)),
the only common exception* I can come up with off the top of my head
is str.find()**, and even that has an exception-throwing cousin,
str.index().


Interesting!  That may take me some getting used to.


Basically, Python tries to avoid returning 'magic' values which you
need to check, but could equally just ignore.

If it can't open a file, it doesn't return None, it complains.

If it can't parse an int from a string, it doesn't return 0 (which it
could return if it's successful) or None or whatever, it complains.

There are times when, say, C# complains but Python doesn't, like trying
to get a substring starting at a position which is off the end of the
source string.

In practice I find that the Python way just works better.
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing" [OT]

2010-10-13 Thread Steven D'Aprano
On Wed, 13 Oct 2010 16:17:19 +0200, Antoon Pardon wrote:

> On Wed, Oct 13, 2010 at 01:20:30PM +, Steven D'Aprano wrote:
>> On Tue, 12 Oct 2010 22:13:26 -0700, RG wrote:
>> 
>> >> The formula: circumference = 2 x pi x radius is taught in primary
>> >> schools, yet it's actually a very difficult formula to prove!
>> > 
>> > What's to prove?  That's the definition of pi.
>> 
>> Incorrect -- it's not necessarily so that the ratio of the
>> circumference to the radius of a circle is always the same number. It
>> could have turned out that different circles had different ratios.
> 
> If that is your concern, you should have reacted to the previous poster
> since in that case his equation couldn't be proven either.

"Very difficult to prove" != "cannot be proven".


> Since by not reacting to the previous poster, you implicitely accepted
> the equation and thus the context in which it is true: euclidean
> geometry. So I don't think that concerns that fall outside this context
> have any relevance.

You've missed the point that, 4000 years later it is easy to take pi for 
granted, but how did anyone know that it was special? After all, there is 
a very similar number 3.1516... but we haven't got a name for it and 
there's no formulae using it. Nor do we have a name for the ratio of the 
radius of a circle to the proportion of the plane that is uncovered when 
you tile it with circles of that radius, because that ratio isn't (as far 
as I know) constant.

Perhaps this will help illustrate what I'm talking about... the 
mathematician Mitchell Feigenbaum discovered in 1975 that, for a large 
class of chaotic systems, the ratio of each bifurcation interval to the 
next approached a constant:

δ = 4.66920160910299067185320382...

Every chaotic system (of a certain kind) will bifurcate at the same rate. 
This constant has been described as being as fundamental to mathematics 
as pi or e. Feigenbaum didn't just *define* this constant, he discovered 
it by *proving* that the ratio of bifurcation intervals was constant. 
Nobody had any idea that this was the case until he did so.


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


how to add patch

2010-10-13 Thread jimgardener
hi
I have some demo python  code hosted on a public host that uses
subversion..and I want to modify one of the files using a patch file
handed to me by another person..How do I do this?Generally I checkout
the code and make the change and then commit again..I have never done
through patch..Can somebody tell me how to do this?
thanks
jim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Steven D'Aprano
On Wed, 13 Oct 2010 17:28:42 +0200, Pascal J. Bourguignon wrote:

>>> But what exactly *is* this number? Is it 0.25, 1.57 or 90?
>>
>> That's the wrong question. It's like asking, what exactly "is" the
>> number twenty-one -- is it "one and twenty", or 21, or 0x15, or 0o25,
>> or 21.0, or 20.999... recurring, or 63/3, or XXI, or 0b10101, or "vinet
>> et un", or any one of many other representations.
> 
> This is not the wrong question.  These are two different things.

Which is why I said it was LIKE asking the second.


> In the case of 0.25, 1.57 or 90, you have elements of the same set of
> real numbers ℝ, which are used to represent the same entity, which IS
> NOT a number, but an angle.  Angles are not in the ℝ set, but in ℝ/2π,
> which is an entirely different set with entirely different properties.

It's quite standard to discuss (say) sin(theta) where theta is an element 
of ℝ. The fact that angles can extent to infinity in both directions is 
kind of fundamental to the idea of saying that the trig functions are 
periodic.

> So you have different pairs of sets and different representationnal
> mapping.  There's very little in common between an angle of 90 degree,
> and the number 21.

Would it have been easier to understand if I had made the analogy between 
angles and (say) time? A time of 1 minute and a time of 60 seconds are 
the same time, regardless of what representation you use for it.


>> Likewise, it doesn't matter whether you write 45° or π/4 radians, the
>> angle you are describing -- the number -- is the same.
> 
> No.  The numbers ARE different.  One number is 45, the other is π/4.
> What is the same, is the angle that is represented.

Fair enough. I worded that badly.




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


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Aleksej Saushev
"BartC"  writes:

> "Thomas A. Russ"  wrote in message
> news:ymi1v7vgyp8@blackcat.isi.edu...
>> torb...@diku.dk (Torben ZÆgidius Mogensen) writes:
>>
>>> Trigonometric functions do take arguments of particular units: radians
>>> or (less often) degrees, with conversion needed if you use the "wrong"
>>> unit.
>>
>> But radians are dimensionless.
>
> But they are still units

1 is a unit. Thanks, Captain.


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


Re: how to add patch

2010-10-13 Thread Jason Swails
On Wed, Oct 13, 2010 at 3:36 PM, jimgardener  wrote:

> hi
> I have some demo python  code hosted on a public host that uses
> subversion..and I want to modify one of the files using a patch file
> handed to me by another person..How do I do this?Generally I checkout
> the code and make the change and then commit again..I have never done
> through patch..Can somebody tell me how to do this?
>

Using patch.  Give the patch file to "patch" via stdin, with some occasional
arguments.

patch -p0 -N < patch_file

If the path to the file is properly specified in the patch file itself, then
this will be automatic.  Otherwise, you'll need to specify the file you want
to patch.  You can see the man page for more details and options.

Good luck!
Jason


> thanks
> jim
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Jason M. Swails
Quantum Theory Project,
University of Florida
Ph.D. Graduate Student
352-392-4032
-- 
http://mail.python.org/mailman/listinfo/python-list


Exceptions are not just for errors (was: My first Python program)

2010-10-13 Thread Ben Finney
Seebs  writes:

> On 2010-10-13, Chris Rebert  wrote:
> > For future reference, the significant majority of things in Python
> > raise exceptions upon encountering errors rather than returning
> > error values of some sort.
>
> Yes.  I'm getting used to that -- it's a bit of a shift, because I'm
> used to exceptions being *exceptional* -- as in, not a failure mode
> you would expect to see happening.

From that expectation, it's an even more fundamental shift. Python
encourages (and tends toward) raising exceptions in any exceptional
circumstance — that is, in any circumstance that isn't the usual
behaviour for the function.

So, for example, an exception (StopIteration) is how iterables signal
that they've finished iterating; but that's not an error, only an
exception. Likewise for the ‘str.index’ example given earlier.

> So for instance, I wouldn't expect to get an exception for EOF,
> because that's not exceptional, that's virtually guaranteed to happen
> whenever you interact with files. I am gonna have to retrain a bit.

EOF is exceptional in that it's not the normal behaviour for “read some
bytes from a file and return them”. EOF is expected – hence it has a
code path for handling that circumstance – but it's not normal.

Another way of thinking about it is that there's no sensible sequence of
bytes to return at EOF, so the Pythonic thing to do is to raise an
exception for this exceptional circumstance.

So your expectations on this point, while not unusual, do need
retraining as you say :-)

-- 
 \   “In the long run nothing can withstand reason and experience, |
  `\and the contradiction which religion offers to both is all too |
_o__)palpable.” —Sigmund Freud |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: My first Python program

2010-10-13 Thread Ben Finney
Seebs  writes:

> 1. If I have a message that I wish to print, it is quite possible that
> message + indentation exceeds 80 lines. What's the idiomatic way to
> solve this? Do I just break the string up into parts, or do I just
> accept that some lines are over 80 characters, or what?

Python borrows from C in that consecutive literal strings are
concatenated in the bytecode::

stderr.write(
"WARNING:"
" Pants on fire\n")

> 2. It warns about **kw, both because the name is short and because of
> the "** magic". I was previously advised that the name "kw" is
> canonical for that usage, in which case, why am I getting linted at?

More conventional is the name ‘kwargs’; of a pair with ‘*args, **kwargs’.

-- 
 \“We have to go forth and crush every world view that doesn't |
  `\believe in tolerance and free speech.” —David Brin |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing" [OT]

2010-10-13 Thread Arnaud Delobelle
Steven D'Aprano  writes:

> On Wed, 13 Oct 2010 16:17:19 +0200, Antoon Pardon wrote:
>
>> On Wed, Oct 13, 2010 at 01:20:30PM +, Steven D'Aprano wrote:
>>> On Tue, 12 Oct 2010 22:13:26 -0700, RG wrote:
>>> 
>>> >> The formula: circumference = 2 x pi x radius is taught in primary
>>> >> schools, yet it's actually a very difficult formula to prove!
>>> > 
>>> > What's to prove?  That's the definition of pi.
>>> 
>>> Incorrect -- it's not necessarily so that the ratio of the
>>> circumference to the radius of a circle is always the same number. It
>>> could have turned out that different circles had different ratios.
>> 
>> If that is your concern, you should have reacted to the previous poster
>> since in that case his equation couldn't be proven either.
>
> "Very difficult to prove" != "cannot be proven".

But in another section of your previous post you argued that it cannot
be proven as it doesn't hold in projective or hyperbolic geometry.

>
>> Since by not reacting to the previous poster, you implicitely accepted
>> the equation and thus the context in which it is true: euclidean
>> geometry. So I don't think that concerns that fall outside this context
>> have any relevance.
>
> You've missed the point that, 4000 years later it is easy to take pi for 
> granted, but how did anyone know that it was special? After all, there is 
> a very similar number 3.1516... but we haven't got a name for it and 
> there's no formulae using it. Nor do we have a name for the ratio of the 
> radius of a circle to the proportion of the plane that is uncovered when 
> you tile it with circles of that radius, because that ratio isn't (as far 
> as I know) constant.
>
> Perhaps this will help illustrate what I'm talking about... the 
> mathematician Mitchell Feigenbaum discovered in 1975 that, for a large 
> class of chaotic systems, the ratio of each bifurcation interval to the 
> next approached a constant:
>
> δ = 4.66920160910299067185320382...
>
> Every chaotic system (of a certain kind) will bifurcate at the same rate. 
> This constant has been described as being as fundamental to mathematics 
> as pi or e. Feigenbaum didn't just *define* this constant, he discovered 
> it by *proving* that the ratio of bifurcation intervals was constant. 
> Nobody had any idea that this was the case until he did so.

But you were claiming that the proposition "C = 2πr is the definition of
π" was false.  Are you claiming that "δ is defined as the ratio of
bifurcation intervals" is false as well?  If you are not, how does this
tie in with the current discussion?

Also, it is very intuitive to think that the ratio of the circumference
of a circle to it radius is constant:

Given two circles with radii r1 and r2, circumferences C1 and C2, one is
obviously the scaled-up version of the other, therefore the ratio of
their circumferences is equal to the ratio of their radii:

C1/C2 = r1/r2

Therefore:

C1/r1 = C2/r2

This constant ratio can be called 2π.  There, it wasn't that hard.  You
can pick nits with this "proof" but it is very simple and is a convincing
enough argument.

This to show that AFAIK (and I'm no historian of Mathematics) there
probably has never been much of a debate about whether the ratio of
circumference to diameter is constant.  OTOH, there were centuries of
intense mathematical labour to find out the value of π.

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


Hyperlink to a file using python

2010-10-13 Thread Pratik Khemka

I want to create a hyperlink in my excel sheet using python such that when you 
click on that link (which is a file name (html file)), the file automatically 
opens. This file is present in the same folder in which the python code file is 
present.

I am using xlwt module

 

 

link=  'abcd.html'
sheet.write(x, y, link, format_style) 

 

x: row y :col 

 

Thanks,

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


Re: Exceptions are not just for errors (was: My first Python program)

2010-10-13 Thread Emmanuel Surleau
> Seebs  writes:
> > On 2010-10-13, Chris Rebert  wrote:
> > > For future reference, the significant majority of things in Python
> > > raise exceptions upon encountering errors rather than returning
> > > error values of some sort.
> > 
> > Yes.  I'm getting used to that -- it's a bit of a shift, because I'm
> > used to exceptions being *exceptional* -- as in, not a failure mode
> > you would expect to see happening.
> 
> From that expectation, it's an even more fundamental shift. Python
> encourages (and tends toward) raising exceptions in any exceptional
> circumstance — that is, in any circumstance that isn't the usual
> behaviour for the function.
> 
> So, for example, an exception (StopIteration) is how iterables signal
> that they've finished iterating; but that's not an error, only an
> exception. Likewise for the ‘str.index’ example given earlier.

I'd say more succintly that Python uses (at times) exception for flow control. 
Whether that's elegant or not is debatable.

Cheers,

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


Re: Scheme as a virtual machine?

2010-10-13 Thread namekuseijin
On 11 out, 08:49, Oleg  Parashchenko  wrote:
> Hello,
>
> I'd like to try the idea that Scheme can be considered as a new
> portable assembler. We could code something in Scheme and then compile
> it to PHP or Python or Java or whatever.
>
> Any suggestions and pointers to existing and related work are welcome.
> Thanks!
>
> My current approach is to take an existing Scheme implementation and
> hijack into its backend. At this moment Scheme code is converted to
> some representation with a minimal set of bytecodes, and it should be
> quite easy to compile this representation to a target language. After
> some research, the main candidates are Gambit, Chicken and CPSCM:
>
> http://uucode.com/blog/2010/09/28/r5rs-scheme-as-a-virtual-machine-i/http://uucode.com/blog/2010/09/28/r5rs-scheme-as-a-virtual-machine-ii/
>
> If there is an interest in this work, I could publish progress
> reports.
>
> --
> Oleg Parashchenko  o...@http://uucode.com/http://uucode.com/blog/ XML, TeX, 
> Python, Mac, Chess

it may be assembler, too bad scheme libs are scattered around written
in far too many different flavors of assembler...

It warms my heart though to realize that Scheme's usual small size and
footprint has allowed for many quality implementations targetting many
different backends, be it x86 assembly, C, javascript or .NET.  Take
python and you have a slow c bytecode interpreter and a slow
bytecode .NET compiler.  Take haskell and its so friggin' huge and
complex that its got its very own scary monolithic gcc.  When you
think of it, Scheme is the one true high-level language with many
quality perfomant backends -- CL has a few scary compilers for native
code, but not one to java, .NET or javascript that I know of...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hyperlink to a file using python

2010-10-13 Thread Chris Rebert
On Wed, Oct 13, 2010 at 1:57 PM, Pratik Khemka  wrote:
> I want to create a hyperlink in my excel sheet using python such that when
> you click on that link (which is a file name (html file)), the file
> automatically opens. This file is present in the same folder in which the
> python code file is present.
> I am using xlwt module

You might consider asking on their newsgroup then:
http://groups.google.com/group/python-excel

Cheers,
Chris
--
"Python Problem solver"; Quite a complementary moniker for the list there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-10-13 Thread Gregory Ewing

RG wrote:
I just couldn't wrap my brain around 
what it meant to square a second.


That's nothing. Magnetic permeability is measured in
newtons per square amp...

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


Re: Hyperlink to a file using python

2010-10-13 Thread Emile van Sebille

On 10/13/2010 1:57 PM Pratik Khemka said...


I want to create a hyperlink in my excel sheet using python such that when you 
click on that link (which is a file name (html file)), the file automatically 
opens. This file is present in the same folder in which the python code file is 
present.

I am using xlwt module





link=  'abcd.html'
sheet.write(x, y, link, format_style)



Hmmm... my excel does that automagically when I
type "http://xx.yy.zz/word.html into a cell.

What happens when you use "http://a.b.c/abcd.html";?

Emile

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


Re: My first Python program

2010-10-13 Thread Hallvard B Furuseth
Ethan Furman writes:
>Seebs wrote:
>>On 2010-10-12, Hallvard B Furuseth  wrote:
 self.type, self.name = None, None
>>
>>> Actually you can write self.type = self.name = None,
>>> though assignment statements are more limited than in C.
>>> (And I think they're assigned left-to-right.)
>
> Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>
> --> a = 2
> --> b = 7
> --> c = 13
> --> a = b = c = 'right to left'
> --> a, b, c
> ('right to left', 'right to left', 'right to left')

Eek.  I just meant to remark it's quite different from C where it means
a=(b=(c='...')), the assignments even happen in left-to-right _order_.
In this Python version anyway.  Not that you'd be setting a string to a
variable:-)

   >>> class Foo(str):
   ...   def __setattr__(*args): print "%s.%s = %s" % args
   ... 
   >>> f, g = Foo("f"), Foo("g")
   >>> f.x = g.y = 3
   f.x = 3
   g.y = 3

  match = re.match('(.*)\(\*([a-zA-Z0-9_]*)\)\((.*)\)', text)
>>
>>> Make a habit of using r'' for strings with lots of backslashes,
>>> like regexps.
>>
>> Hmm.  There's an interesting question -- does this work as-is? I'm
>> assuming it must or it would have blown up on me pretty badly, so
>> presumably those backslashes are getting passed through untouched
>> already.  But if that's just coincidence (they happen not to be valid
>> \-sequences), I should definitely fix that.
>
> Unknown backslash sequences are passed through as-is.

Personally I don't want to need to remember, I'm already confusing the
backslash rules of different languges.  Often you can just ask Python
what it thinks of such things, as I did with open("nonesuch"), and
then either imitate the answer or use it to help you zoom in on it in
the doc now that you know the rough answer to look for.  So,

$ python
>>> '(.*)\(\*([a-zA-Z0-9_]*)\)\((.*)\)'
'(.*)\\(\\*([a-zA-Z0-9_]*)\\)\\((.*)\\)'

Thus I'd personally spell it that way or with r'':

r'(.*)\(\*([a-zA-Z0-9_]*)\)\((.*)\)'

Note that [a-zA-Z0-9_] is equivalent to \w or [\w] in Python 2 unless
you give a LOCALE or UNICODE flag, and in Python 3 if you give the
ASCII flag.

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


PyCharm

2010-10-13 Thread Robert H
Since the new IDE from Jetbrains is out I was wondering if "you" are
using it and what "you" think about it.

I have to start learning Python for a project at work and I am looking
around for options.

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


  1   2   >