new release 0.38 of OpenOpt, FuncDesigner, SpaceFuncs, DerApproximator

2012-03-15 Thread dmitrey
Hi all,
I'm glad to inform you about new release 0.38 (2012-March-15):

OpenOpt:

interalg can handle discrete variables
interalg can handle multiobjective problems (MOP)
interalg can handle problems with parameters fixedVars/freeVars
Many interalg improvements and some bugfixes
Add another EIG solver: numpy.linalg.eig
New LLSP solver pymls with box bounds handling

FuncDesigner:

Some improvements for sum()
Add funcs tanh, arctanh, arcsinh, arccosh
Can solve EIG built from derivatives of several functions,
obtained by automatic differentiation by FuncDesigner

SpaceFuncs:

Add method point.symmetry(Point|Line|Plane)
Add method LineSegment.middle
Add method Point.rotate(Center, angle)

DerApproximator:

Minor changes

See http://openopt.org for more details

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

Support the Python Software Foundation:
http://www.python.org/psf/donations/


Re: Enchancement suggestion for argparse: intuit type from default

2012-03-15 Thread Cameron Simpson
On 15Mar2012 12:22, Ben Finney ben+pyt...@benfinney.id.au wrote:
| Roy Smith r...@panix.com writes:
|  I'll admit I hadn't considered that, but I don't see it as a major
|  problem. The type intuition could be designed to only work for types
|  other than NoneType.
| 
| −1, then. It's growing too many special cases, and is no longer simple
| to describe, so that indicates it's probably a bad idea.

If `type` is not supplied and `default` is present and not None, `type`
shall be the type of `default`.

That seems straightforward to me. It's a single sentence, easy to read
and understand, and potentially saves a lot of code verbiage (gratuitous
type= prarameters). I say gratuitous because unless `default` is a
sentinel for no option supplied, the `type` should always match
type(default). Or am I wrong about that?

Cheers,
-- 
Cameron Simpson c...@zip.com.au DoD#743
http://www.cskk.ezoshosting.com/cs/

You only live once in life, but if you do it right, once is enough!
- Rob Castro r...@columbia.edu
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is readable

2012-03-15 Thread alex23
Rick Johnson rantingrickjohn...@gmail.com wrote:
 However, when we are talking about the Python
 programming language readable simply means: neophyte readable.
 That is, readable to someone with little or no experience with the
 language.

Nonsense. List comprehensions are not immediately obvious to new
Python users. The functionality of 'with' requires an understanding of
context managers. Python's readability has more to do with simplifying
code maintenance.

The idea that Python code has to be obvious to non-programmers is an
incorrect and dangerous one.


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


Re: Is it technically possible to give Python option of naming process of running script?

2012-03-15 Thread xliiv
  Like the topic.. .
  I use Python a lot, both Windows and Linux, and it's little weird to have 
  many python process without fast distinction which is what.
 
  I've no idea if it's even possible on Windows. On Linux, what you want
  is the prctl function, which (AFAIK) isn't directly available.
 
  Google is your friend, though. Question's already been asked on Stack
  Overflow and such, and has a few answers. Nothing that looks
  cut-and-dried ready, but several that might work.
 
 The question of how to set the application name comes up somewhat
 regularly. It would be awfully nice if there was a way for python
 applications to set their application name.  It's especially useful
 for daemons, and makes it much easier when you can kill them by name
 instead of having to look up the PID.
 
 It seems like an excellent thing to add to the os module.
 
  Look for 'prctl' and 'PR_SET_NAME', which are the C-level function
  and constant that do the job; a cursory examination of PyPI shows a
  module with prctl in the name, so that may be of value.


I did google, I've played with Exemaker (it works perfect, but not py3) and 
i've seen questions on Stackoverflow.
The thing I mean is a build feature of python to give such a name. Not 3rd part 
or etc. like Grant Edwards said. Is it possible?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it technically possible to give Python option of naming process of running script?

2012-03-15 Thread xliiv
  Like the topic.. .
  I use Python a lot, both Windows and Linux, and it's little weird to have 
  many python process without fast distinction which is what.
 
  I've no idea if it's even possible on Windows. On Linux, what you want
  is the prctl function, which (AFAIK) isn't directly available.
 
  Google is your friend, though. Question's already been asked on Stack
  Overflow and such, and has a few answers. Nothing that looks
  cut-and-dried ready, but several that might work.
 
 The question of how to set the application name comes up somewhat
 regularly. It would be awfully nice if there was a way for python
 applications to set their application name.  It's especially useful
 for daemons, and makes it much easier when you can kill them by name
 instead of having to look up the PID.
 
 It seems like an excellent thing to add to the os module.
 
  Look for 'prctl' and 'PR_SET_NAME', which are the C-level function
  and constant that do the job; a cursory examination of PyPI shows a
  module with prctl in the name, so that may be of value.


I did google, I've played with Exemaker (it works perfect, but not py3) and 
i've seen questions on Stackoverflow. 
The thing I mean is a build feature of python to give such a name. Not 3rd part 
or etc. like Grant Edwards said. Is it possible?
-- 
http://mail.python.org/mailman/listinfo/python-list


pyserial for GPS data

2012-03-15 Thread Arun p das
I have a USB GPS dongle using this for getting  position information. I
installed gpsd daemon so that any clients can read data from that. It is
working fine
used xgps, cgps as clients.

*gpsd -n -N -D2 /dev/ttyUSB0 *

import gps, os, time
g = gps.gps(mode=gps.WATCH_NEWSTYLE)
while 1:
os.system('clear')
g.poll()
#if gps.PACKET_SET:
g.stream()
print 'latitude ' , g.fix.latitude
print 'longitude ' , g.fix.longitude
print 'time utc ' , g.utc,' + ', g.fix.time


Used the following program to read gps data but it is not giving accurate
readings as cgps,xgps clients. I tried to read directly from the serial
port using the following program but its giving non printable characters as
output as it should return something like

$GPRMC,199304.973,3248.7780,N,11355.7832,W,1,06,02.2,25722.5,M,,,*00

*import serial*
*ser = serial.Serial( port='/dev/ttyUSB0', baudrate=4800,timeout=1) *
*while True:*
* line=ser.read()*
* print line,*
*f.close()*
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Enchancement suggestion for argparse: intuit type from default

2012-03-15 Thread Robert Kern

On 3/15/12 5:59 AM, Cameron Simpson wrote:

On 15Mar2012 12:22, Ben Finneyben+pyt...@benfinney.id.au  wrote:
| Roy Smithr...@panix.com  writes:
|  I'll admit I hadn't considered that, but I don't see it as a major
|  problem. The type intuition could be designed to only work for types
|  other than NoneType.
|
| −1, then. It's growing too many special cases, and is no longer simple
| to describe, so that indicates it's probably a bad idea.

If `type` is not supplied and `default` is present and not None, `type`
shall be the type of `default`.

That seems straightforward to me. It's a single sentence, easy to read
and understand, and potentially saves a lot of code verbiage (gratuitous
type= prarameters). I say gratuitous because unless `default` is a
sentinel for no option supplied, the `type` should always match
type(default). Or am I wrong about that?


Yes. Not all type(default) types can be called with a string to produce a valid 
value. Note that type= is really a misnomer. argparse doesn't really want a 
type object there; it wants a converter function that takes a string to an object.


--
Robert Kern

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

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


Re: Enchancement suggestion for argparse: intuit type from default

2012-03-15 Thread Cameron Simpson
On 15Mar2012 10:06, Robert Kern robert.k...@gmail.com wrote:
| On 3/15/12 5:59 AM, Cameron Simpson wrote:
|  On 15Mar2012 12:22, Ben Finneyben+pyt...@benfinney.id.au  wrote:
|  | Roy Smithr...@panix.com  writes:
|  |  I'll admit I hadn't considered that, but I don't see it as a major
|  |  problem. The type intuition could be designed to only work for types
|  |  other than NoneType.
|  |
|  | −1, then. It's growing too many special cases, and is no longer simple
|  | to describe, so that indicates it's probably a bad idea.
| 
|  If `type` is not supplied and `default` is present and not None, `type`
|  shall be the type of `default`.
| 
|  That seems straightforward to me. [... sentinels aside...] the `type`
|  should always match type(default). Or am I wrong about that?
| 
| Yes. Not all type(default) types can be called with a string to produce a 
valid 
| value. Note that type= is really a misnomer. argparse doesn't really want a 
| type object there; it wants a converter function that takes a string to an 
object.

Aha. Still, you could change the docs to say you only need type= if
type(default) _isn't_ useful as the string-value converter.
-- 
Cameron Simpson c...@zip.com.au DoD#743
http://www.cskk.ezoshosting.com/cs/

As your attorney, it is my duty to inform you that it is not important that
you understand what I'm doing or why you're paying me so much money. What's
important is that you continue to do so.
- Hunter S. Thompson's Samoan Attorney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is readable

2012-03-15 Thread Kiuhnm

On 3/15/2012 7:23, alex23 wrote:

Rick Johnsonrantingrickjohn...@gmail.com  wrote:

However, when we are talking about the Python
programming language readable simply means: neophyte readable.
That is, readable to someone with little or no experience with the
language.


Nonsense. List comprehensions are not immediately obvious to new
Python users. The functionality of 'with' requires an understanding of
context managers. Python's readability has more to do with simplifying
code maintenance.


Let's try that.
Show me an example of list comprehensions and with (whatever they are).

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


Re: Python is readable

2012-03-15 Thread Chris Angelico
On Thu, Mar 15, 2012 at 9:44 PM, Kiuhnm
kiuhnm03.4t.yahoo...@mail.python.org wrote:
 Let's try that.
 Show me an example of list comprehensions and with (whatever they are).

I'll do a list comp, because they lend themselves well to one-liners.
what_am_i = '\n'.join([%X\t%c%(i,i) for i in range(128)])

Okay, that one also uses printf formatting, which may be a smidge
obscure. Here's a simpler example:

what_am_i = [x*x for x in range(11)]

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


Re: Python is readable

2012-03-15 Thread Thomas Rachel

Am 15.03.2012 11:44 schrieb Kiuhnm:


Let's try that.
Show me an example of list comprehensions and with (whatever they are).


with open(filename, w) as f:
f.write(stuff)


with lock:
do_something_exclusively()


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


Re: Python is readable

2012-03-15 Thread Kiuhnm

On 3/15/2012 11:50, Chris Angelico wrote:

On Thu, Mar 15, 2012 at 9:44 PM, Kiuhnm
kiuhnm03.4t.yahoo...@mail.python.org  wrote:

Let's try that.
Show me an example of list comprehensions and with (whatever they are).


I'll do a list comp, because they lend themselves well to one-liners.
what_am_i = '\n'.join([%X\t%c%(i,i) for i in range(128)])


A few conjectures:
1) '\n' is an object and join one of its methods;
2) [...] is a list comprehension;
3) that 'for' suggests that range isn't (or doesn't return) a list but 
an iterator;
4) points 2 and 3 suggest that [...] builds a list (or array?) by 
querying an iterator.

5) %X\t%(i,i) is probably equivalent to the C-like Perl's
  sprintf(%X\t%c, i, i)

So what_am_i is a simple ASCII table.


Okay, that one also uses printf formatting, which may be a smidge
obscure. Here's a simpler example:

what_am_i = [x*x for x in range(11)]


what_am_i = 0, 1, 4, 9, ..., 100

Your first example suggests that range(n) is a sequence iterator which 
returns, if queried n times,

  0,...,n-1
(which is a bit counterintuitive, IMHO).

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


Re: Python is readable

2012-03-15 Thread Chris Angelico
On Thu, Mar 15, 2012 at 10:27 PM, Kiuhnm
kiuhnm03.4t.yahoo...@mail.python.org wrote:
 On 3/15/2012 11:50, Chris Angelico wrote:
 I'll do a list comp, because they lend themselves well to one-liners.
 what_am_i = '\n'.join([%X\t%c%(i,i) for i in range(128)])


 A few conjectures:
 1) '\n' is an object and join one of its methods;
 2) [...] is a list comprehension;
 3) that 'for' suggests that range isn't (or doesn't return) a list but an
 iterator;
 4) points 2 and 3 suggest that [...] builds a list (or array?) by querying
 an iterator.
 5) %X\t%(i,i) is probably equivalent to the C-like Perl's
  sprintf(%X\t%c, i, i)

 So what_am_i is a simple ASCII table.

Correct. Actually, there's a few differences between Python 2 and 3;
in Py2, range() returns a list, but in Py3 an iterable object. But
'for' will happily iterate over a list.

 Okay, that one also uses printf formatting, which may be a smidge
 obscure. Here's a simpler example:

 what_am_i = [x*x for x in range(11)]

 what_am_i = 0, 1, 4, 9, ..., 100

Correct again.

 Your first example suggests that range(n) is a sequence iterator which
 returns, if queried n times,
  0,...,n-1
 (which is a bit counterintuitive, IMHO).

It's a little odd, perhaps, if seen in a vacuum. But everything counts
from zero - list indices, etc - so it makes sense for range(len(lst))
to return indices valid for lst.

List comps are pretty readable if you know how programming languages
work. Python need not be readable by everyone and his grandmother, and
it does a fairly good job of being grokkable to someone who has a few
ranks in Coding. (Yeah, I'm a DD nerd. )

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


Re: Python is readable

2012-03-15 Thread Kiuhnm

On 3/15/2012 12:14, Thomas Rachel wrote:

Am 15.03.2012 11:44 schrieb Kiuhnm:


Let's try that.
Show me an example of list comprehensions and with (whatever they
are).


with open(filename, w) as f:
f.write(stuff)


Here f is created before executing the block and destroyed right after 
leaving the block. f's destructor will probably close the file handle.



with lock:
do_something_exclusively()


It's clear what it does, but I don't know if that's special syntax. 
Maybe objects can have two special methods that are called respect. on 
entering and leaving the with-block.
Or, more likely, lock creates an object which keeps the lock acquired. 
The lock is released when we leave the block.

So we could inspect the lock with
  with lock as l:
  inspect l...
  do_some.

BTW, aren't those ':' redundant?

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


Re: Python is readable

2012-03-15 Thread Kiuhnm

On 3/15/2012 12:47, Chris Angelico wrote:

On Thu, Mar 15, 2012 at 10:27 PM, Kiuhnm

Your first example suggests that range(n) is a sequence iterator which
returns, if queried n times,
  0,...,n-1
(which is a bit counterintuitive, IMHO).


It's a little odd, perhaps, if seen in a vacuum. But everything counts
from zero - list indices, etc - so it makes sense for range(len(lst))
to return indices valid for lst.


Maybe range uses [...) intervals? So range(a,b) is a,a+1,a+2,...,b-1 and
range(b) is just short-hand for range(0,b)?


List comps are pretty readable if you know how programming languages
work. Python need not be readable by everyone and his grandmother, and
it does a fairly good job of being grokkable to someone who has a few
ranks in Coding. (Yeah, I'm a DD nerd. )


I like what I've seen so far.

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


Re: Python is readable

2012-03-15 Thread Chris Angelico
On Thu, Mar 15, 2012 at 10:59 PM, Kiuhnm
kiuhnm03.4t.yahoo...@mail.python.org wrote:
 On 3/15/2012 12:47, Chris Angelico wrote:
 It's a little odd, perhaps, if seen in a vacuum. But everything counts
 from zero - list indices, etc - so it makes sense for range(len(lst))
 to return indices valid for lst.

 Maybe range uses [...) intervals? So range(a,b) is a,a+1,a+2,...,b-1 and
 range(b) is just short-hand for range(0,b)?

Yup. It's amazing how accurate your conjectures are - it's almost like
you've been reading the docs! :D But yeah, that's pretty logical IMHO;
and having gotten used to [) intervals in many areas of computing,
I've come to find [] intervals disconcerting. Bible passages are
described as, for instance, John 14:5-7, which is a three-verse
passage (5, 6, 7), even though 7-5=2.

However, inclusive-inclusive intervals have the benefit that they
don't require the element beyond the last to be indexable. This is
important if you're working with something that takes up all of
addressable memory - going back to the IBM PCs on which I learned to
code, you could use one 64KB segment for an array, but then there's no
way for a 16-bit integer to indicate past the end.

 List comps are pretty readable if you know how programming languages
 work. Python need not be readable by everyone and his grandmother, and
 it does a fairly good job of being grokkable to someone who has a few
 ranks in Coding. (Yeah, I'm a DD nerd. )

 I like what I've seen so far.

Python has its problems, but it's a good language. I personally prefer
to delimit blocks of code with braces than with indentation, and I
also prefer explicit declaration of variables (yes, it's extra work,
but you can have infinitely nested scopes and easily-caught syntax
errors when you misspell one), but they're relatively minor. One of my
favorite aspects of Python is that *everything* is an object. There's
no magic syntax that gives you a piece of an object, or something
special about variables that contain this, that, or the other. A
literal list [like, this, one] can be used in exactly the same ways as
the name of a variable containing a list or a function call returning
a list - there is no difference. Oh how I yearn for that when working
in C++ or PHP!

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


Re: Is there a ConfigParser which keeps comments

2012-03-15 Thread Steven W. Orr

On 3/14/2012 6:07 AM, Gelonida N wrote:

Hi,


At the moment I use ConfigParser
http://docs.python.org/library/configparser.html
for one of my applications.


Now I'm looking for a library, which behaves like config parser, but
with one minor difference.

The write() mehtod should keep existing comments.

Does anybody know or implement something like this or is there as
switrch, that I overlooked in hte documentaiton.




I use ConfigObj.

--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python is readable

2012-03-15 Thread Ben Finney
Chris Angelico ros...@gmail.com writes:

 Yup. It's amazing how accurate your conjectures are - it's almost like
 you've been reading the docs! :D But yeah, that's pretty logical IMHO;
 and having gotten used to [) intervals in many areas of computing,
 I've come to find [] intervals disconcerting. Bible passages are
 described as, for instance, John 14:5-7, which is a three-verse
 passage (5, 6, 7), even though 7-5=2.

Another good reason to advocate for proper typography. “John 14:5–7”
indicates a range (because it uses U+2013 EN DASH), whereas “7−5”
indicates subtraction (because it uses U+2212 MINUS SIGN). A hyphen (‘-’
U+002D) is inappropriate in either case.

-- 
 \  “He that would make his own liberty secure must guard even his |
  `\ enemy from oppression.” —Thomas Paine |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is readable

2012-03-15 Thread Chris Angelico
On Thu, Mar 15, 2012 at 11:31 PM, Ben Finney ben+pyt...@benfinney.id.au wrote:
 Another good reason to advocate for proper typography. John 14:5-7
 indicates a range (because it uses U+2013 EN DASH), whereas 7-5
 indicates subtraction (because it uses U+2212 MINUS SIGN). A hyphen ('-'
 U+002D) is inappropriate in either case.

Heh. Yes, but when you're seeking the size of a range, you use
subtraction. The fact that the en dash and minus sign are both often
represented in ASCII with a hyphen is pure coincidence.

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


ANN: python-ldap 2.4.9

2012-03-15 Thread Michael Ströder

Find a new release of python-ldap:

  http://pypi.python.org/pypi/python-ldap/2.4.8

python-ldap provides an object-oriented API to access LDAP directory
servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for
that purpose. Additionally it contains modules for other LDAP-related
stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema).

Project's web site:

  http://www.python-ldap.org/

Ciao, Michael.


Released 2.4.9 2012-03-14

Changes since 2.4.8:

Lib/
* ldapobject.ReconnectLDAPObject.reconnect() now does kind of
  an internal locking to pause other threads while reconnecting
  is pending.
* Changes to bind- and startTLS-related operation methods of
  class ReconnectLDAPObject for more robustness
* New constant ldap.OPT_NAMES_DICT contains mapping from
  integer to variable name for all option-related constants.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python is readable

2012-03-15 Thread Ben Finney
Chris Angelico ros...@gmail.com writes:

 On Thu, Mar 15, 2012 at 11:31 PM, Ben Finney ben+pyt...@benfinney.id.au 
 wrote:
  Another good reason to advocate for proper typography. John 14:5-7
  indicates a range (because it uses U+2013 EN DASH), whereas 7-5
  indicates subtraction (because it uses U+2212 MINUS SIGN). A hyphen
  ('-' U+002D) is inappropriate in either case.

 Heh. Yes, but when you're seeking the size of a range, you use
 subtraction.

Not the size of an *inclusive* range, such as a range indicated by use
of an en dash :-)

 The fact that the en dash and minus sign are both often represented in
 ASCII with a hyphen is pure coincidence.

Hopefully, the fact that your quoting of my text munged the characters
down to ASCII is also pure coincidence, and is soon to be corrected at
your end? Or has your client program not joined the rest of us in the
third millennium with Unicode?

-- 
 \ “Geeks like to think that they can ignore politics. You can |
  `\leave politics alone, but politics won't leave you alone.” |
_o__) —Richard M. Stallman, 2002-07-26 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Enchancement suggestion for argparse: intuit type from default

2012-03-15 Thread Roy Smith
In article mailman.665.1331806024.3037.python-l...@python.org,
 Robert Kern robert.k...@gmail.com wrote:

 Yes. Not all type(default) types can be called with a string to produce a 
 valid 
 value. Note that type= is really a misnomer. argparse doesn't really want a 
 type object there; it wants a converter function that takes a string to an 
 object.

Orthogonal to my original suggestion, I agree that this is misnamed.  
I'm +1 on the idea of renaming it to conversion= or something like that 
(we'd need to keep type= around as a deprecated synonym for backwards 
compatability).  It's really hard to get your head around type=open.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is readable

2012-03-15 Thread Chris Angelico
On Fri, Mar 16, 2012 at 12:16 AM, Ben Finney ben+pyt...@benfinney.id.au wrote:
 Chris Angelico ros...@gmail.com writes:

 On Thu, Mar 15, 2012 at 11:31 PM, Ben Finney ben+pyt...@benfinney.id.au 
 wrote:
  Another good reason to advocate for proper typography. John 14:5-7
  indicates a range (because it uses U+2013 EN DASH), whereas 7-5
  indicates subtraction (because it uses U+2212 MINUS SIGN). A hyphen
  ('-' U+002D) is inappropriate in either case.

 Heh. Yes, but when you're seeking the size of a range, you use
 subtraction.

 Not the size of an *inclusive* range, such as a range indicated by use
 of an en dash :-)

Yes you do, you just have to add one to it. You still use subtraction. :)

 The fact that the en dash and minus sign are both often represented in
 ASCII with a hyphen is pure coincidence.

 Hopefully, the fact that your quoting of my text munged the characters
 down to ASCII is also pure coincidence, and is soon to be corrected at
 your end? Or has your client program not joined the rest of us in the
 third millennium with Unicode?

It's gmail, and I don't know why it folded everything down. I've told
it to cast everything to text (to avoid the stupid look you sometimes
get with nested replies to HTML-formatted emails), and I guess it
decided to go ASCII. Your mail displayed just fine, it was something
in the reply mechanism.

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


Re: Python is readable

2012-03-15 Thread Ben Finney
Chris Angelico ros...@gmail.com writes:

 On Fri, Mar 16, 2012 at 12:16 AM, Ben Finney ben+pyt...@benfinney.id.au 
 wrote:
  Hopefully, the fact that your quoting of my text munged the
  characters down to ASCII is also pure coincidence, and is soon to be
  corrected at your end? Or has your client program not joined the
  rest of us in the third millennium with Unicode?

 It's gmail, and I don't know why it folded everything down.

Ah. The answer is “No”, then. Gmail (from what I can tell of receiving
messages from it) is terrible at Unicode, and for that reason among many
others is a poor choice for interacting with modern forums.

I recommend you add your voice to those complaining at Gmail's support
team about poor Unicode support, and meanwhile use a better-maintained
free-software client.

-- 
 \ “Quidquid latine dictum sit, altum viditur.”  (“Whatever is |
  `\  said in Latin, sounds profound.”) —anonymous |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is readable

2012-03-15 Thread Mark Lawrence

On 15/03/2012 11:48, Kiuhnm wrote:

On 3/15/2012 12:14, Thomas Rachel wrote:

Am 15.03.2012 11:44 schrieb Kiuhnm:


Let's try that.
Show me an example of list comprehensions and with (whatever they
are).


with open(filename, w) as f:
f.write(stuff)


Here f is created before executing the block and destroyed right after
leaving the block. f's destructor will probably close the file handle.


with lock:
do_something_exclusively()


It's clear what it does, but I don't know if that's special syntax.
Maybe objects can have two special methods that are called respect. on
entering and leaving the with-block.
Or, more likely, lock creates an object which keeps the lock acquired.
The lock is released when we leave the block.
So we could inspect the lock with
with lock as l:
inspect l...
do_some.

BTW, aren't those ':' redundant?

Kiuhnm


Nope.

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit 
(Intel)] on win32

Type help, copyright, credits or license for more information.
 with open(filename, w) as f
  File stdin, line 1
with open(filename, w) as f
  ^
SyntaxError: invalid syntax

--
Cheers.

Mark Lawrence.

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


Re: Python is readable

2012-03-15 Thread Alec Taylor
On Fri, Mar 16, 2012 at 1:06 AM, Mark Lawrence breamore...@yahoo.co.uk wrote:
 Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on
 win32
 Type help, copyright, credits or license for more information.

 with open(filename, w) as f
  File stdin, line 1

    with open(filename, w) as f
                                  ^
 SyntaxError: invalid syntax

 --
 Cheers.

 Mark Lawrence.


Erred for me also; but under f:

Python 2.7.3rc1 (default, Feb 24 2012, 21:28:59) [MSC v.1500 64 bit
(AMD64)] on win32
Type help, copyright, credits or license for more information.
 with open(filename, w) as f
  File stdin, line 1
with open(filename, w) as f
  ^
SyntaxError: invalid syntax
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is readable

2012-03-15 Thread Kiuhnm

On 3/15/2012 13:21, Chris Angelico wrote:

On Thu, Mar 15, 2012 at 10:59 PM, Kiuhnm
kiuhnm03.4t.yahoo...@mail.python.org  wrote:

On 3/15/2012 12:47, Chris Angelico wrote:

It's a little odd, perhaps, if seen in a vacuum. But everything counts
from zero - list indices, etc - so it makes sense for range(len(lst))
to return indices valid for lst.


Maybe range uses [...) intervals? So range(a,b) is a,a+1,a+2,...,b-1 and
range(b) is just short-hand for range(0,b)?


Yup. It's amazing how accurate your conjectures are - it's almost like
you've been reading the docs! :D


Come on... that was easy! :)


But yeah, that's pretty logical IMHO;
and having gotten used to [) intervals in many areas of computing,
I've come to find [] intervals disconcerting. Bible passages are
described as, for instance, John 14:5-7, which is a three-verse
passage (5, 6, 7), even though 7-5=2.


Common people use mainly inclusive intervals as far as I can tell.
For instance, from and to are inclusive.
They could tell you they don't like your intervals because 8-5+1 = 4 
instead of 3.



However, inclusive-inclusive intervals have the benefit that they
don't require the element beyond the last to be indexable. This is
important if you're working with something that takes up all of
addressable memory - going back to the IBM PCs on which I learned to
code, you could use one 64KB segment for an array, but then there's no
way for a 16-bit integer to indicate past the end.


But you lose the empty interval (a,a). You're forced to use (a,a-1) or 
something similar. There's always a drawback.



List comps are pretty readable if you know how programming languages
work. Python need not be readable by everyone and his grandmother, and
it does a fairly good job of being grokkable to someone who has a few
ranks in Coding. (Yeah, I'm a DD nerd. )


I like what I've seen so far.


Python has its problems, but it's a good language. I personally prefer
to delimit blocks of code with braces than with indentation,


I, on the other hand, prefer indentation. I find braces redundant (in 
fact, I never use them in pseudo-code).



and I
also prefer explicit declaration of variables (yes, it's extra work,
but you can have infinitely nested scopes and easily-caught syntax
errors when you misspell one), but they're relatively minor.


I usually declare my variables but close to where I need them.


One of my
favorite aspects of Python is that *everything* is an object. There's
no magic syntax that gives you a piece of an object, or something
special about variables that contain this, that, or the other. A
literal list [like, this, one] can be used in exactly the same ways as
the name of a variable containing a list or a function call returning
a list - there is no difference. Oh how I yearn for that when working
in C++ or PHP!


Don't worry. Soon you'll be using C++0x :)))

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


Re: Python is readable

2012-03-15 Thread Kiuhnm

On 3/15/2012 15:06, Mark Lawrence wrote:

On 15/03/2012 11:48, Kiuhnm wrote:

On 3/15/2012 12:14, Thomas Rachel wrote:

Am 15.03.2012 11:44 schrieb Kiuhnm:


Let's try that.
Show me an example of list comprehensions and with (whatever they
are).


with open(filename, w) as f:
f.write(stuff)


Here f is created before executing the block and destroyed right after
leaving the block. f's destructor will probably close the file handle.


with lock:
do_something_exclusively()


It's clear what it does, but I don't know if that's special syntax.
Maybe objects can have two special methods that are called respect. on
entering and leaving the with-block.
Or, more likely, lock creates an object which keeps the lock acquired.
The lock is released when we leave the block.
So we could inspect the lock with
with lock as l:
inspect l...
do_some.

BTW, aren't those ':' redundant?

Kiuhnm


Nope.

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit
(Intel)] on win32
Type help, copyright, credits or license for more information.
  with open(filename, w) as f
File stdin, line 1
with open(filename, w) as f
^
SyntaxError: invalid syntax


Ok, so they're mandatory, but I was mainly talking of design. Why are 
they needed?


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


Re: Python is readable

2012-03-15 Thread Tim Golden

On 15/03/2012 14:19, Kiuhnm wrote:

On 3/15/2012 15:06, Mark Lawrence wrote:

On 15/03/2012 11:48, Kiuhnm wrote:

BTW, aren't those ':' redundant?

Kiuhnm


Nope.

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit
(Intel)] on win32
Type help, copyright, credits or license for more information.
 with open(filename, w) as f
File stdin, line 1
with open(filename, w) as f
^
SyntaxError: invalid syntax


Ok, so they're mandatory, but I was mainly talking of design. Why are
they needed?

Kiuhnm


http://docs.python.org/faq/design.html#why-are-colons-required-for-the-if-while-def-class-statements

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


Re: Python is readable

2012-03-15 Thread Duncan Booth
Kiuhnm kiuhnm03.4t.yahoo.it wrote:

 BTW, aren't those ':' redundant?
 

They are required by the grammar, but in a sense you are correct. You could 
modify Python's grammar to make the colons optional and still keep it 
unambiguous but that would make it harder for other tools (such as text 
editors or indeed humans) to understand.

A little bit of redundancy in the grammar is seen as a good way to minimise 
errors.

-- 
Duncan Booth http://kupuguy.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list


client ssl verification

2012-03-15 Thread Robin Becker
I'm trying to do client ssl verification with code that looks like the sample 
below. I am able to reach and read urls that are secure and have no client 
certificate requirement OK. If I set explicit_check to True then verbose output 
indicates that the server certs are being checked fine ie I see the correct cert 
details and am able to check them.


However, when I try to reach an apache location like

Location /media/secret
sslverifyclient require
sslverifydepth 10
/Location

I am getting an error from  urllib2 that goes like this

urllib2.py, line 1148, in do_open
raise URLError(err)
URLError: urlopen error [Errno 1] _ssl.c:1347: error:14094418:SSL 
routines:SSL3_READ_BYTES:tlsv1 alert unknown ca


I am using the server.crt and server.key (both in PEM format) from the target 
server itself; I reasoned that should be the easiest combo for the client  
server to match, but I am obviously wrong. Any obvious stupidities to be pointed 
out? I suppose I could create a new cert/key based on a self signed ca, but that 
would not work properly for the other parts of the server.



import socket, ssl, fnmatch, datetime, urllib2, httplib
verbose=False

# wraps https connections with ssl certificate verification
class SecuredHTTPSHandler(urllib2.HTTPSHandler):
  def 
__init__(self,key_file=None,cert_file=None,ca_certs=None,explicit_check=False):
class SecuredHTTPSConnection(httplib.HTTPSConnection):
  def connect(self):
# overrides the version in httplib so that we do
#  certificate verification
sock = socket.create_connection((self.host, self.port), self.timeout)
if self._tunnel_host:
  self.sock = sock
  self._tunnel()
# wrap the socket using verification with the root
#  certs in ca_certs
if verbose:
  print ca_certs, key_file, cert_file
self.sock = ssl.wrap_socket(sock,
  cert_reqs=ssl.CERT_REQUIRED,
  ca_certs=ca_certs,
  keyfile=key_file,
  certfile=cert_file,
  )
if explicit_check:
  cert = self.sock.getpeercert()
  if verbose:
import pprint
pprint.pprint(cert)
  for key,field in cert.iteritems():
if key=='subject':
  sd = dict([x[0] for x in field])
  certhost = sd.get('commonName')
  if not fnmatch.fnmatch(self.host,certhost):
raise ssl.SSLError(Host name '%s' doesn't match certificate host 
'%s'
 % (self.host, certhost))
  if verbose:
print 'matched %s to %s'  % (self.host,certhost)
elif key=='notAfter':
  now = datetime.datetime.now()
  crttime = datetime.datetime.strptime(field,'%b %d %H:%M:%S %Y %Z')
  if verbose:
print 'crttime=%s now=%s' % (crttime,now)
  if now=crttime:
raise ssl.SSLError(Host '%s' certificate expired on %s
   % (self.host, field))
self.specialized_conn_class = SecuredHTTPSConnection
urllib2.HTTPSHandler.__init__(self)

  def https_open(self, req):
return self.do_open(self.specialized_conn_class, req)

def secureDataGet(uri,ca_certs='cacert.pem',key_file=None,cert_file=None, 
explicit_check=False):
  https_handler = SecuredHTTPSHandler(key_file=key_file,cert_file=cert_file,
ca_certs=ca_certs,explicit_check=explicit_check)
  url_opener = urllib2.build_opener(https_handler)
  handle = url_opener.open(uri)
  response = handle.readlines()
  handle.close()
  return response



--
Robin Becker

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


Re: Python is readable

2012-03-15 Thread Chris Angelico
On Fri, Mar 16, 2012 at 1:16 AM, Kiuhnm
kiuhnm03.4t.yahoo...@mail.python.org wrote:
 Don't worry. Soon you'll be using C++0x :)))

I use gcc/g++ with most of the new features enabled. There's some
pretty handy features in it. Frankly, though, if I'd known about
Cython when I started the current project, I would have argued to
write it all in Python and Cify (is that a word?) the most
performance-critical sections afterwards, instead of writing it in
C++. It'd be a lot of hassle to change it now, but if anyone else is
looking at writing a large project in C for performance, I would
strongly recommend writing in Python or Pike first. (Some day, I'm
going to have to actually try Cython. But I know enough of
embedding/extending Python to know that the technique would definitely
be viable, and Cython can only make it easier.)

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


Re: Python is readable

2012-03-15 Thread Kiuhnm

On 3/15/2012 15:23, Duncan Booth wrote:

Kiuhnmkiuhnm03.4t.yahoo.it  wrote:


BTW, aren't those ':' redundant?



They are required by the grammar, but in a sense you are correct. You could
modify Python's grammar to make the colons optional and still keep it
unambiguous but that would make it harder for other tools (such as text
editors or indeed humans) to understand.


Sorry, but I can't see how it would make it harder for humans to 
understand. Are there particular situations you're referring to?


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


Re: Python is readable

2012-03-15 Thread Kiuhnm

On 3/15/2012 15:29, Chris Angelico wrote:

On Fri, Mar 16, 2012 at 1:16 AM, Kiuhnm
kiuhnm03.4t.yahoo...@mail.python.org  wrote:

Don't worry. Soon you'll be using C++0x :)))


I use gcc/g++ with most of the new features enabled. There's some
pretty handy features in it. Frankly, though, if I'd known about
Cython when I started the current project, I would have argued to
write it all in Python and Cify (is that a word?) the most
performance-critical sections afterwards, instead of writing it in
C++.


Wise words. Indeed, I was joking :)
I don't like what C++ is becoming. C++ should be rewritten from scratch 
but then who would use it?


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


Re: Python is readable

2012-03-15 Thread Robert Kern

On 3/15/12 2:30 PM, Kiuhnm wrote:

On 3/15/2012 15:23, Duncan Booth wrote:

Kiuhnmkiuhnm03.4t.yahoo.it wrote:


BTW, aren't those ':' redundant?



They are required by the grammar, but in a sense you are correct. You could
modify Python's grammar to make the colons optional and still keep it
unambiguous but that would make it harder for other tools (such as text
editors or indeed humans) to understand.


Sorry, but I can't see how it would make it harder for humans to understand. Are
there particular situations you're referring to?


There were usability studies done on one of Python's indentation-based 
ancestors, ABC. Those studies found, empirically, that having the colons helped 
people read and understand the code faster.


--
Robert Kern

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

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


Re: Python is readable

2012-03-15 Thread Chris Angelico
On Fri, Mar 16, 2012 at 1:30 AM, Kiuhnm
kiuhnm03.4t.yahoo...@mail.python.org wrote:
 Sorry, but I can't see how it would make it harder for humans to understand.
 Are there particular situations you're referring to?

In a trivial example, it's mostly just noise:

if a == b# who needs the colon?
print(c)

But when your condition is more complicated, it's cleaner to
explicitly mark the end of the condition. Also, Python allows you to
put a simple body on the same line as the if, which is very handy:

if a == b: print(c)

Without the colon, this would be awkward to parse. And the bash style
of using actual statement separators feels really weird, although it
does mean that the newline is truly optional.

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


Re: Python is readable

2012-03-15 Thread Kiuhnm

On 3/15/2012 15:28, Tim Golden wrote:

On 15/03/2012 14:19, Kiuhnm wrote:

On 3/15/2012 15:06, Mark Lawrence wrote:

On 15/03/2012 11:48, Kiuhnm wrote:

BTW, aren't those ':' redundant?

Kiuhnm


Nope.

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit
(Intel)] on win32
Type help, copyright, credits or license for more information.
 with open(filename, w) as f
File stdin, line 1
with open(filename, w) as f
^
SyntaxError: invalid syntax


Ok, so they're mandatory, but I was mainly talking of design. Why are
they needed?

Kiuhnm


http://docs.python.org/faq/design.html#why-are-colons-required-for-the-if-while-def-class-statements


The second one is slightly easier to read because it's 
syntax-highlighted. Was that on purpose?
By the way, the more elaborate parsing consists of looking for an 
END_OF_LINE followed by one or more spaces. It doesn't sound that 
complicated.

And what about an editor which indent when you press the spacebar or tab?

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


Re: Python is readable

2012-03-15 Thread Chris Angelico
On Fri, Mar 16, 2012 at 1:55 AM, Kiuhnm
kiuhnm03.4t.yahoo...@mail.python.org wrote:
 By the way, the more elaborate parsing consists of looking for an
 END_OF_LINE followed by one or more spaces. It doesn't sound that
 complicated.

Only in the trivial case. What if you want to break your condition
over multiple lines? (Although you have to parenthesize or backslash,
so that's still unambig.) It's helpful to be explicit.

 And what about an editor which indent when you press the spacebar or tab?

Sure, but a good editor helps out by noticing that you did something
that begs for indentation. If I put an open brace, SciTE will indent -
very simple rule. With Python, if there were no colon markers, it
would be quite complicated to figure out whether or not to indent;
with the colons, it's simply if/while/etc followed by text followed
by colon, and then no further non-comment text. (This sounds involved.
It's not. It's right enough. -- Lady Blanche)

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


Re: Python is readable

2012-03-15 Thread Kiuhnm

On 3/15/2012 15:48, Chris Angelico wrote:

On Fri, Mar 16, 2012 at 1:30 AM, Kiuhnm
kiuhnm03.4t.yahoo...@mail.python.org  wrote:

Sorry, but I can't see how it would make it harder for humans to understand.
Are there particular situations you're referring to?


In a trivial example, it's mostly just noise:

if a == b# who needs the colon?
 print(c)

But when your condition is more complicated, it's cleaner to
explicitly mark the end of the condition. Also, Python allows you to
put a simple body on the same line as the if, which is very handy:

if a == b: print(c)

Without the colon, this would be awkward to parse. And the bash style
of using actual statement separators feels really weird, although it
does mean that the newline is truly optional.


I had thought about the single-line case. What I hadn't thought about is 
that Python strives to be as regular as possible, so having different 
cases just for saving one keystroke isn't worth it.


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


Re: Python is readable

2012-03-15 Thread Robert Kern

On 3/15/12 2:55 PM, Kiuhnm wrote:

On 3/15/2012 15:28, Tim Golden wrote:



http://docs.python.org/faq/design.html#why-are-colons-required-for-the-if-while-def-class-statements


The second one is slightly easier to read because it's syntax-highlighted. Was
that on purpose?


No, it's an unintended side effect. The (automated) syntax highlighting was 
added to the FAQ much, much later than that entry was written. The syntax 
highlighting tool does not recognize the first example as Python, so it does not 
apply Python syntax highlighting to it.


--
Robert Kern

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

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


Re: Python is readable

2012-03-15 Thread Chris Angelico
On Fri, Mar 16, 2012 at 2:05 AM, Kiuhnm
kiuhnm03.4t.yahoo...@mail.python.org wrote:
 I had thought about the single-line case. What I hadn't thought about is
 that Python strives to be as regular as possible, so having different cases
 just for saving one keystroke isn't worth it.

Yep. Have you read the Zen of Python?

 import this
(trimmed for brevity)
Explicit is better than implicit.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
In the face of ambiguity, refuse the temptation to guess.

Omitting the colon is definitely a not-special-enough case.

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


Re: Python is readable

2012-03-15 Thread Roy Smith
In article mailman.678.1331821755.3037.python-l...@python.org,
 Chris Angelico ros...@gmail.com wrote:

 I use gcc/g++ with most of the new features enabled. There's some
 pretty handy features in it. Frankly, though, if I'd known about
 Cython when I started the current project, I would have argued to
 write it all in Python and Cify (is that a word?) the most
 performance-critical sections afterwards, instead of writing it in
 C++.

+1.

With the exception of the client-side javascript, virtually 100% of the 
application code behind songza.com is python.  We use django, tornado, 
and gunicorn (all pure python).  The ORM layer (mongoengine) is pure 
python.  Of course, there's plenty of C/C++ code in the database 
(MongoDB), HTTP proxies (nginx and haproxy), and search engine (Xapian), 
but the core application code is all python.  About 80,000 lines worth.

Every time we look at performance, we discover the same thing.  The time 
spent running python code is insignificant.  It's all about network I/O 
and database queries.  The only time we ever see any significant time 
running python code is when we do something stupid and write some O(n^2) 
code that can be replaced by a more appropriate algorithm.

While it's nice to know that we've got the ability to write extensions 
in C, not once have we ever felt the need.  I suppose if you're running 
a CPU-bound application, that might not be the case, but surprisingly 
few applications really are compute bound these days.

I had an interesting experience the other day.  We had a job applicant 
implement one of our coding tests in Java.  It's a data mining exercise 
where you need to generate some summary statistics from a 700,000 line 
log file we give you.  My Python version takes under a second.  His Java 
version came up with the right numbers but took 2 minutes.  I looked at 
his code and didn't any any obvious problem.  It turned out he used a 
regex that started with '.*', and apparently the Java regex library 
implements that badly.  Eliminating the leading '.*' got his Java 
running in the same time as my Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is readable

2012-03-15 Thread Kiuhnm

On 3/15/2012 15:43, Robert Kern wrote:

On 3/15/12 2:30 PM, Kiuhnm wrote:

On 3/15/2012 15:23, Duncan Booth wrote:

Kiuhnmkiuhnm03.4t.yahoo.it wrote:


BTW, aren't those ':' redundant?



They are required by the grammar, but in a sense you are correct. You
could
modify Python's grammar to make the colons optional and still keep it
unambiguous but that would make it harder for other tools (such as text
editors or indeed humans) to understand.


Sorry, but I can't see how it would make it harder for humans to
understand. Are
there particular situations you're referring to?


There were usability studies done on one of Python's indentation-based
ancestors, ABC. Those studies found, empirically, that having the colons
helped people read and understand the code faster.


Here's what Guido van Rossum writes about it:
Python’s use of indentation comes directly from ABC, but this idea 
didn’t originate with ABC--it had already been promoted by Donald Knuth 
and was a well-known concept of programming style. (The occam 
programming language also used it.) However, ABC’s authors did invent 
the use of the colon that separates the lead-in clause from the indented 
block.


 After early user testing without the colon, it was discovered that 
the meaning of the indentation was unclear to beginners being taught the 
first steps of programming. 


The addition of the colon clarified it significantly: the colon somehow 
draws attention to what follows and ties the phrases before and after it 
together in just the right way.


If that passage is correct, those studies don't say that adding the 
colon increases the readability, but that it makes more sense to 
beginners who don't even know what indentation is.


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


Re: Python is readable

2012-03-15 Thread Chris Angelico
On Fri, Mar 16, 2012 at 2:14 AM, Roy Smith r...@panix.com wrote:
 While it's nice to know that we've got the ability to write extensions
 in C, not once have we ever felt the need.  I suppose if you're running
 a CPU-bound application, that might not be the case, but surprisingly
 few applications really are compute bound these days.

My boss and I have these discussions now and then. A topic of
performance comes up, and we debate whether or not, for instance, it's
worth doing a separate check of an input file to see if it's
properly-formed UTF-8 before parsing it (this is in PHP, or it'd be
easy - just do a UTF-8 decode and work with Unicode). The debate
ended, as they inevitably do, with We're talking about a file that
someone's uploaded to us, so it won't matter. Whatever processing we
do is massively dwarfed by network time, and both scale linearly with
the size of the file.

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


Re: Python is readable

2012-03-15 Thread Roy Smith
In article mailman.685.1331825254.3037.python-l...@python.org,
 Chris Angelico ros...@gmail.com wrote:

 We're talking about a file that someone's uploaded to us, so it 
 won't matter. Whatever processing we do is massively dwarfed by 
 network time, and both scale linearly with the size of the file.

That last part (both scaling linearly) may not be true.  There's an 
overhead of one RTT (Round Trip Time) to open a TCP connection.  Add at 
least (handwave) one more RTT if you're negotiating encryption (i.e. 
https).  If you're sending lots of small files, this can easily swamp 
the data transfer time.

The single biggest optimization we've made recently was using a 
persistent https connection to an external data provider.  Fortunately, 
the truly awesome requests library (http://docs.python-requests.org/) 
made that trivial to implement.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is readable

2012-03-15 Thread Thomas Rachel

Am 15.03.2012 12:48 schrieb Kiuhnm:

On 3/15/2012 12:14, Thomas Rachel wrote:

Am 15.03.2012 11:44 schrieb Kiuhnm:


Let's try that.
Show me an example of list comprehensions and with (whatever they
are).


with open(filename, w) as f:
f.write(stuff)


Here f is created before executing the block and destroyed right after
leaving the block. f's destructor will probably close the file handle.


No, that is the point here: with calls __enter__ on entry and __exit__ 
on, well, exit.


In the case of files, __enter__ doesn't probably do anything special, 
but returns the object again in order to be assigned to f. In __exit__, 
the file is closed.


with open(/tmp/filename, w) as f:
print f
print f

open file '/tmp/filename', mode 'w' at 0xb74e6d30
closed file '/tmp/filename', mode 'w' at 0xb74e6d30

So after the with clause, f is actually closed, but still present as object.


with lock:
do_something_exclusively()



It's clear what it does, but I don't know if that's special syntax.


If you call with special syntax, it is.


Maybe objects can have two special methods that are called respect. on
entering and leaving the with-block.


Exactly, see above.

Here, on entry __enter__ is called which acquires the lock.
__exit__ releases it again.



Or, more likely, lock creates an object which keeps the lock acquired.
The lock is released when we leave the block.
So we could inspect the lock with
with lock as l:
inspect l...
do_some.


Or just inspect l - I don't know if a lock's __enter__ methos returns it 
again for assignment with as...



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


Re: Python is readable

2012-03-15 Thread Alec Taylor
On Fri, Mar 16, 2012 at 1:16 AM, Kiuhnm
kiuhnm03.4t.yahoo...@mail.python.org wrote:
 On 3/15/2012 13:21, Chris Angelico wrote:

 On Thu, Mar 15, 2012 at 10:59 PM, Kiuhnm
 kiuhnm03.4t.yahoo...@mail.python.org  wrote:

 On 3/15/2012 12:47, Chris Angelico wrote:

 It's a little odd, perhaps, if seen in a vacuum. But everything counts
 from zero - list indices, etc - so it makes sense for range(len(lst))
 to return indices valid for lst.


 Maybe range uses [...) intervals? So range(a,b) is a,a+1,a+2,...,b-1 and
 range(b) is just short-hand for range(0,b)?


 Yup. It's amazing how accurate your conjectures are - it's almost like
 you've been reading the docs! :D


 Come on... that was easy! :)


 But yeah, that's pretty logical IMHO;
 and having gotten used to [) intervals in many areas of computing,
 I've come to find [] intervals disconcerting. Bible passages are
 described as, for instance, John 14:5-7, which is a three-verse
 passage (5, 6, 7), even though 7-5=2.


 Common people use mainly inclusive intervals as far as I can tell.
 For instance, from and to are inclusive.
 They could tell you they don't like your intervals because 8-5+1 = 4 instead
 of 3.


 However, inclusive-inclusive intervals have the benefit that they
 don't require the element beyond the last to be indexable. This is
 important if you're working with something that takes up all of
 addressable memory - going back to the IBM PCs on which I learned to
 code, you could use one 64KB segment for an array, but then there's no
 way for a 16-bit integer to indicate past the end.


 But you lose the empty interval (a,a). You're forced to use (a,a-1) or
 something similar. There's always a drawback.

 List comps are pretty readable if you know how programming languages
 work. Python need not be readable by everyone and his grandmother, and
 it does a fairly good job of being grokkable to someone who has a few
 ranks in Coding. (Yeah, I'm a DD nerd. )


 I like what I've seen so far.


 Python has its problems, but it's a good language. I personally prefer
 to delimit blocks of code with braces than with indentation,


 I, on the other hand, prefer indentation. I find braces redundant (in fact,
 I never use them in pseudo-code).


 and I
 also prefer explicit declaration of variables (yes, it's extra work,
 but you can have infinitely nested scopes and easily-caught syntax
 errors when you misspell one), but they're relatively minor.


 I usually declare my variables but close to where I need them.


 One of my
 favorite aspects of Python is that *everything* is an object. There's
 no magic syntax that gives you a piece of an object, or something
 special about variables that contain this, that, or the other. A
 literal list [like, this, one] can be used in exactly the same ways as
 the name of a variable containing a list or a function call returning
 a list - there is no difference. Oh how I yearn for that when working
 in C++ or PHP!


 Don't worry. Soon you'll be using C++0x :)))

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

C++0x? You mean C++11? :P

On that note, is Python upgrading to use C11? :V
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it technically possible to give Python option of naming process of running script?

2012-03-15 Thread Dave Angel

On 03/15/2012 03:26 AM, xliiv wrote:

Like the topic.. .
I use Python a lot, both Windows and Linux, and it's little weird to have many 
python process without fast distinction which is what.




I did google, I've played with Exemaker (it works perfect, but not py3) and 
i've seen questions on Stackoverflow.
The thing I mean is a build feature of python to give such a name. Not 3rd part 
or etc. like Grant Edwards said. Is it possible?


How about simply using cp to copy the python executable, run chmod +x on 
it, and run that one?  Then ps would list it as the new name, not as python.


i tried it on /usr/bin/python2.7but I see no reason the same 
approach won't work on 3.x  Note, I copied it to a new name in the same 
directory, which may be important.  or not.


--

DaveA

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


Pragmas, foreign keys in sqlite3?

2012-03-15 Thread llanitedave
Several questions here, but they're related.

I'm trying to incorporate an sqlite3 database that was created using
Sqliteman1.2.2.  I don't know what version of sqlite3 that one uses,
but it seems to have ignored any attempts to create foreign keys for
its tables.

I'm using Python 2.7.2, and I know that the sqlite3 version that it
contains is 3.7.7.  Therefore, it should be able to handle foreign
keys.  Where I'm clueless is about how to get that information out of
it, and how to implement or add foreign keys to existing tables.

Is there some way to use the sqlite PRAGMA command from within python?

I tried connecting to the database and got

 cr.execute('''PRAGMA foreign_keys;''')
sqlite3.Cursor object at 0xb7335720

 using inspect.getmembers() I got a huge list of everything; it lets
me see that there's no foreign key created, but I can't get that
particular tuple separated out, and I have no idea how to add them.

Do I need to recreate the entire database structure from scratch?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Style question (Poll)

2012-03-15 Thread Jon Clements
On Wednesday, 14 March 2012 21:16:05 UTC, Terry Reedy  wrote:
 On 3/14/2012 4:49 PM, Arnaud Delobelle wrote:
  On 14 March 2012 20:37, Croephacroe...@gmail.com  wrote:
  Which is preferred:
 
  for value in list:
if not value is another_value:
  value.do_something()
  break
 
 Do you really mean 'is' or '=='?
 
 If you mean x is not y, write it that way.
 'not x is y' can be misread and misunderstood, depending on whether
 the 'is' is true or not.
 
   not 1 is 1
 False
   not (1 is 1)
 False
   (not 1) is 1
 False
 
 Does not matter how read.
 
   not (1 is 0)
 True
   (not 1) is 0
 False
   not 1 is 0
 True
 
 Does matter how read.
 
  if list and not list[0] is another_value:
list[0].do_something()
 
 Or
 try:
value = mylist[0]
if value is not another_value: value.dosomething
 except IndexError:
pass
 
 I would not do this in this case of index 0, but if the index were a 
 complicated expression or expensive function call, making 'if list' an 
 inadequate test, I might.
 
  Hard to say, since they don't do the same thing :)
 
  I suspect you meant:
 
  for value in list:
  if not value is another_value:
  value.do_something()
  break
 
  I always feel uncomfortable with this because it's misleading: a loop
  that never loops.
 
 I agree. Please do not do this in public ;-).
 
 -- 
 Terry Jan Reedy

I'm not sure it's efficient or even if I like it, but it avoids try/except and 
the use of a for loop.

if next( iter(mylist), object() ) is not another_value:
# ...

Just my 2p,

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


Questions about the use of descriptors.

2012-03-15 Thread Steven W. Orr

Question 1:

I have a class A with one attribute and I define __get__ and __set__ for that 
class. Then I create another class B that uses it.


Why does B require that the instance of A be a class variable in B and not 
created as an instance variable in __init__?


E.g.,
# This works fine.
class Truth(object):
def __init__(self):
self.is_slave = False

def __get__(self, obj, objtype):
return self.is_slave

def __set__(self, obj, val):
if not self.is_slave and val:
self.is_slave = val


class TruthHolder(object):
IsSlave = Truth()

def set_truth(self):
self.IsSlave = True

tt = TruthHolder()
print tt.IsSlave
tt.IsSlave = True
print tt.IsSlave
tt.IsSlave = False
print tt.IsSlave


But if I change TruthHolder to not start as a class variable

class TruthHolder(object):
def __init__(self):
self.IsSlave = Truth()

def set_truth(self):
self.IsSlave = True

it doesn't seem to use descriptor methods of Truth. It's just using the 
default setter and getter of TruthHolder.


Question2:

Is it the case that people only use descriptors for classes with single 
attributes? Or is it more frequent that descriptors are used with classes that 
have multiple attributes?


I feel like this is powerful juju, but I'm not getting when I should be using 
property and when I should be using descriptors.


General note: I see really simple examples in my searches, but I'd like to see 
a good practical example that has just a bit more meat on it.


--
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
--
http://mail.python.org/mailman/listinfo/python-list


Context Manager getting str instead of AttributeError instance

2012-03-15 Thread Prasad, Ramit
So I have a context manager used to catch errors

def __exit__( self, exceptionClass, exception, tracebackObject ):
if isinstance( exception, self.exceptionClasses ):
 #do something here

Normally exception would be the exception instance, but for 
AttributeError it seems to be a string instead. 

1) Why is AttributeError different than the other built-ins
in this respect?
2) Are there other standard errors like this (I know
that SystemExit is different as well)?
3) Taking into account that I want to include subclasses of 
classes listed in self.exceptionClasses, Is there a better check I can use?

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is readable

2012-03-15 Thread Mark Lawrence

On 15/03/2012 16:01, Alec Taylor wrote:


C++0x? You mean C++11? :P

On that note, is Python upgrading to use C11? :V


Not for Windows given 
http://mail.python.org/pipermail/python-dev/2012-February/116258.html. 
I've no idea regarding *nix, os x or whatever.


--
Cheers.

Mark Lawrence.

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


Re: Python is readable

2012-03-15 Thread Devin Jeanpierre
On Wed, Mar 14, 2012 at 8:27 PM, Chris Angelico ros...@gmail.com wrote:
 On Thu, Mar 15, 2012 at 10:54 AM, Arnaud Delobelle arno...@gmail.com wrote:
 I don't know this book and there may be a pedagogical reason for the
 implementation you quote, but pairwise_sum is probably better
 implemented in Python 3.X as:

 def pairwise_sum(list1, list2):
    return [x1 + x2 for x1, x2 in zip(list1, list2)]

 Okay, here's something for debate.

 Should the readability of a language be gauged on the basis of its
 standard library, or should you be comparing actual code?

Actual code often uses the standard library.

 For instance, a quine in C can be fairly complex and messy, and it can
 be unobvious what it's doing - but in HQ9+ it's easy. Is it fair to
 compare on that basis, or should you actually implement the same /
 equivalent code in each before judging?

It's fair. But it's also fair to note that the comparison is silly,
because the easiness of writing quines doesn't correspond with the
easiness of doing productive things.


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


RE: Python is readable

2012-03-15 Thread Prasad, Ramit
   Hopefully, the fact that your quoting of my text munged the
   characters down to ASCII is also pure coincidence, and is soon to be
   corrected at your end? Or has your client program not joined the
   rest of us in the third millennium with Unicode?

Outlook showed the EN DASH but your MINUS SIGN and hyphen were the same for me. 
(UTF-8)

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Questions about the use of descriptors.

2012-03-15 Thread Ian Kelly
On Thu, Mar 15, 2012 at 11:32 AM, Steven W. Orr ste...@syslang.net wrote:
 Question 1:

 I have a class A with one attribute and I define __get__ and __set__ for
 that class. Then I create another class B that uses it.

 Why does B require that the instance of A be a class variable in B and not
 created as an instance variable in __init__?

Because that's the way descriptors work -- you put them on a class,
and they modify the behavior of instances of that class w.r.t. the
attribute they're stored in.

If you store an object that implements the descriptor protocol in an
instance attribute, then it is treated as ordinary data, not as a
descriptor (which would often be undesirable).  For example, this
behavior is the reason that you can store functions in instance
attributes without having them automagically turn into methods of the
instance:

def make_color(name):
if name == 'red':
return (255, 0, 0)
elif name == 'green':
return (0, 255, 0)
elif name == 'blue':
return (0, 0, 255)
else:
raise ValueError('Unsupported color %r' % name)

class FactoryUser(object):

def __init__(self, factory):
self.factory = factory

def show_blue(self):
color = self.factory('blue')
print(color)

FactoryUser(make_color).show_blue()

Here, if self.factory were treated as a descriptor, then it would
become a method of the FactoryUser instance instead of just an
arbitrary function, and the call self.factory('blue') would fail,
because it would try to pass self in as the first argument to
make_color, which it is not expecting since it is not a member of
FactoryUser.


 Question2:

 Is it the case that people only use descriptors for classes with single
 attributes? Or is it more frequent that descriptors are used with classes
 that have multiple attributes?

property is a convenient shorthand for a one-off descriptor.  I use
descriptor classes instead when I have a generic behavior that I want
to use across multiple attributes, either on a single class or in
multiple classes.  As a simple, real example, I have a wxPython app
with some classes for dialog windows, each of which contain one or
more text controls, and I want to be able to access the contents of
those text controls as attributes.  I could create a whole bunch of
properties, each of which does basically the same thing, or I could
just use this descriptor class:

class TextDescriptor(object):

def __init__(self, control_name):
self._control_name = control_name

def __get__(self, instance, owner):
if instance is not None:
return getattr(instance, self._control_name).GetValue()

def __set__(self, instance, value):
getattr(instance, self._control_name).ChangeValue(value)

Then to create the individual properties, all I have to do is this:

class MyDialog(wx.Dialog):

name = TextDescriptor('_name')
description = TextDescriptor('_description')
address = TextDescriptor('_address')

def __init__(self, ...):
# Build the dialog along with the _name, _description, and
_address controls...

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


Re: Is it technically possible to give Python option of naming process of running script?

2012-03-15 Thread Grant Edwards
On 2012-03-15, Dave Angel d...@davea.name wrote:
 On 03/15/2012 03:26 AM, xliiv wrote:
 Like the topic.. .
 I use Python a lot, both Windows and Linux, and it's little weird to have 
 many python process without fast distinction which is what.


 I did google, I've played with Exemaker (it works perfect, but not py3) and 
 i've seen questions on Stackoverflow.
 The thing I mean is a build feature of python to give such a name. Not 3rd 
 part or etc. like Grant Edwards said. Is it possible?

 How about simply using cp to copy the python executable, run chmod +x on 
 it, and run that one?  Then ps would list it as the new name, not as python.

That's rather a waste of memory.  Better to use a link.  That way the
executable can still be shared by multiple programs and won't be
duplicated in memory.

 i tried it on /usr/bin/python2.7but I see no reason the same 
 approach won't work on 3.x  Note, I copied it to a new name in the same 
 directory, which may be important.  or not.

Seems like an awfully obtuse way of doing things -- I don't really
want to have 15 different copies of Python (or even links), and it
requires root privleges every time you want to run a Python program
with the correct name.

-- 
Grant Edwards   grant.b.edwardsYow! Can I have an IMPULSE
  at   ITEM instead?
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Context Manager getting str instead of AttributeError instance

2012-03-15 Thread Peter Otten
Prasad, Ramit wrote:

 So I have a context manager used to catch errors
 
 def __exit__( self, exceptionClass, exception, tracebackObject ):
 if isinstance( exception, self.exceptionClasses ):
  #do something here
 
 Normally exception would be the exception instance, but for
 AttributeError it seems to be a string instead.

I don't think so:

 class A(object):
... def __enter__(self): return self
... def __exit__(self, *args): print args
... 
 with A() as a:
... a.x
... 
(type 'exceptions.AttributeError', AttributeError('A' object has no 
attribute 'x',), traceback object at 0x7f57b70f22d8)
Traceback (most recent call last):
  File stdin, line 2, in module
AttributeError: 'A' object has no attribute 'x'
 
 1) Why is AttributeError different than the other built-ins
 in this respect?
 2) Are there other standard errors like this (I know
 that SystemExit is different as well)?
 3) Taking into account that I want to include subclasses of
 classes listed in self.exceptionClasses, Is there a better check I can
 use?


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


RE: Context Manager getting str instead of AttributeError instance

2012-03-15 Thread Prasad, Ramit
 Prasad, Ramit wrote:
 
  So I have a context manager used to catch errors
 
  def __exit__( self, exceptionClass, exception, tracebackObject ):
  if isinstance( exception, self.exceptionClasses ):
   #do something here
 
  Normally exception would be the exception instance, but for
  AttributeError it seems to be a string instead.
 
 I don't think so:
 
  class A(object):
 ... def __enter__(self): return self
 ... def __exit__(self, *args): print args
 ...
  with A() as a:
 ... a.x
 ...
 (type 'exceptions.AttributeError', AttributeError('A' object has no
 attribute 'x',), traceback object at 0x7f57b70f22d8)
 Traceback (most recent call last):
   File stdin, line 2, in module
 AttributeError: 'A' object has no attribute 'x'
 
  1) Why is AttributeError different than the other built-ins
  in this respect?
  2) Are there other standard errors like this (I know
  that SystemExit is different as well)?
  3) Taking into account that I want to include subclasses of
  classes listed in self.exceptionClasses, Is there a better check I can
  use?

Not sure why mine behaves differently:
Python 2.6.6 (r266:84292, Dec 17 2010, 12:36:53) [MSC v.1500 32 bit (Intel)] on 
win32
 
 class A(object):
... def __enter__(self): return self
... def __exit__(self, *args): print args
... 
 with A() as a:
... a.x
... 
(type 'exceptions.AttributeError', 'A' object has no attribute 'x', 
traceback object at 0x1817F648)
AttributeError: 'A' object has no attribute 'x'

As you can see, I am getting a string while you are not. 

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is readable

2012-03-15 Thread Serhiy Storchaka
15.03.12 16:19, Kiuhnm написав(ла):
 Ok, so they're mandatory, but I was mainly talking of design. Why are they 
 needed?

http://python-history.blogspot.com/2011/07/karin-dewar-indentation-and-colon.html

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


Re: Python is readable

2012-03-15 Thread Kiuhnm

On 3/15/2012 16:08, Chris Angelico wrote:

On Fri, Mar 16, 2012 at 1:55 AM, Kiuhnm
kiuhnm03.4t.yahoo...@mail.python.org  wrote:

By the way, the more elaborate parsing consists of looking for an
END_OF_LINE followed by one or more spaces. It doesn't sound that
complicated.


Only in the trivial case. What if you want to break your condition
over multiple lines? (Although you have to parenthesize or backslash,
so that's still unambig.) It's helpful to be explicit.


You said it yourself. Just look out for parentheses or backslashes.
C and C++ editors do that all the time with single-statement 
control-flow constructs.



And what about an editor which indent when you press the spacebar or tab?


Sure, but a good editor helps out by noticing that you did something
that begs for indentation. If I put an open brace, SciTE will indent -
very simple rule.


What about braces in strings? There's always some parsing going on and 
since you probably want syntax highlighting and maybe code 
autocompletion, what's the problem with missing colons?


Moreover, I think that
  if (
  
  ):
  
  
  
is not very readable anyway.

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


Re: Context Manager getting str instead of AttributeError instance

2012-03-15 Thread Ian Kelly
On Thu, Mar 15, 2012 at 1:10 PM, Prasad, Ramit
ramit.pra...@jpmorgan.com wrote:
 Prasad, Ramit wrote:

  So I have a context manager used to catch errors
 
  def __exit__( self, exceptionClass, exception, tracebackObject ):
      if isinstance( exception, self.exceptionClasses ):
           #do something here
 
  Normally exception would be the exception instance, but for
  AttributeError it seems to be a string instead.

 I don't think so:

  class A(object):
 ...     def __enter__(self): return self
 ...     def __exit__(self, *args): print args
 ...
  with A() as a:
 ...     a.x
 ...
 (type 'exceptions.AttributeError', AttributeError('A' object has no
 attribute 'x',), traceback object at 0x7f57b70f22d8)
 Traceback (most recent call last):
   File stdin, line 2, in module
 AttributeError: 'A' object has no attribute 'x'

  1) Why is AttributeError different than the other built-ins
  in this respect?
  2) Are there other standard errors like this (I know
  that SystemExit is different as well)?
  3) Taking into account that I want to include subclasses of
  classes listed in self.exceptionClasses, Is there a better check I can
  use?

 Not sure why mine behaves differently:
 Python 2.6.6 (r266:84292, Dec 17 2010, 12:36:53) [MSC v.1500 32 bit (Intel)] 
 on win32

 class A(object):
 ...     def __enter__(self): return self
 ...     def __exit__(self, *args): print args
 ...
 with A() as a:
 ...     a.x
 ...
 (type 'exceptions.AttributeError', 'A' object has no attribute 'x', 
 traceback object at 0x1817F648)
 AttributeError: 'A' object has no attribute 'x'

 As you can see, I am getting a string while you are not.

Looks like a version difference.  I don't have Python 2.6 handy to
test on, but I get a str in Python 2.5 and an AttributeError instance
in Python 2.7.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Context Manager getting str instead of AttributeError instance

2012-03-15 Thread Prasad, Ramit
  ...
  (type 'exceptions.AttributeError', 'A' object has no attribute 'x',
 traceback object at 0x1817F648)
  AttributeError: 'A' object has no attribute 'x'
 
  As you can see, I am getting a string while you are not.
 
Ian Kelly said: 
 Looks like a version difference.  I don't have Python 2.6 handy to
 test on, but I get a str in Python 2.5 and an AttributeError instance
 in Python 2.7.

Thanks Ian, that was the key! I guess I will just have to work around it.
Any suggestions? I am thinking about just creating a blank instance of 
the error class since that the class gets passed successfully.


Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Context Manager getting str instead of AttributeError instance

2012-03-15 Thread Ian Kelly
On Thu, Mar 15, 2012 at 2:25 PM, Prasad, Ramit
ramit.pra...@jpmorgan.com wrote:
  ...
  (type 'exceptions.AttributeError', 'A' object has no attribute 'x',
 traceback object at 0x1817F648)
  AttributeError: 'A' object has no attribute 'x'
 
  As you can see, I am getting a string while you are not.

Ian Kelly said:
 Looks like a version difference.  I don't have Python 2.6 handy to
 test on, but I get a str in Python 2.5 and an AttributeError instance
 in Python 2.7.

 Thanks Ian, that was the key! I guess I will just have to work around it.
 Any suggestions? I am thinking about just creating a blank instance of
 the error class since that the class gets passed successfully.

Well, for what you want to do, I don't think you need an instance at
all -- just use issubclass instead of isinstance:

def __exit__( self, exceptionClass, exception, tracebackObject ):
   if issubclass( exceptionClass, self.exceptionClasses ):
#do something here

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


RE: Context Manager getting str instead of AttributeError instance

2012-03-15 Thread Peter Otten
Prasad, Ramit wrote:

 Prasad, Ramit wrote:
 
  So I have a context manager used to catch errors
 
  def __exit__( self, exceptionClass, exception, tracebackObject ):
  if isinstance( exception, self.exceptionClasses ):
   #do something here
 
  Normally exception would be the exception instance, but for
  AttributeError it seems to be a string instead.
 
 I don't think so:
 
  class A(object):
 ... def __enter__(self): return self
 ... def __exit__(self, *args): print args
 ...
  with A() as a:
 ... a.x
 ...
 (type 'exceptions.AttributeError', AttributeError('A' object has no
 attribute 'x',), traceback object at 0x7f57b70f22d8)
 Traceback (most recent call last):
   File stdin, line 2, in module
 AttributeError: 'A' object has no attribute 'x'
 
  1) Why is AttributeError different than the other built-ins
  in this respect?
  2) Are there other standard errors like this (I know
  that SystemExit is different as well)?
  3) Taking into account that I want to include subclasses of
  classes listed in self.exceptionClasses, Is there a better check I can
  use?
 
 Not sure why mine behaves differently:
 Python 2.6.6 (r266:84292, Dec 17 2010, 12:36:53) [MSC v.1500 32 bit
 (Intel)] on win32
 
 class A(object):
 ... def __enter__(self): return self
 ... def __exit__(self, *args): print args
 ...
 with A() as a:
 ... a.x
 ...
 (type 'exceptions.AttributeError', 'A' object has no attribute 'x',
 traceback object at 0x1817F648) AttributeError: 'A' object has no
 attribute 'x'
 
 As you can see, I am getting a string while you are not.

Ah, it's a bug:

http://bugs.python.org/issue7853

Unfortunately it is to severe to fix in a bugfix release. You could work 
around it with an issubclass() test on the first argument.


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


Re: Python is readable

2012-03-15 Thread Arnaud Delobelle
On 15 March 2012 00:27, Chris Angelico ros...@gmail.com wrote:
 On Thu, Mar 15, 2012 at 10:54 AM, Arnaud Delobelle arno...@gmail.com wrote:
 I don't know this book and there may be a pedagogical reason for the
 implementation you quote, but pairwise_sum is probably better
 implemented in Python 3.X as:

 def pairwise_sum(list1, list2):
    return [x1 + x2 for x1, x2 in zip(list1, list2)]

 Okay, here's something for debate.

 Should the readability of a language be gauged on the basis of its
 standard library, or should you be comparing actual code?

But here's the code posted by the OP:

--- Python ---
def pairwise_sum(list1, list2):
   result = []
   for i in range(len(list1)):
   result.append(list1[i] + list2[i])
   return result
--- ---

The code I posted uses one builtin function (zip), the code posted by
the OP uses two (range and len).  Neither uses the standard library.

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


Re: Enchancement suggestion for argparse: intuit type from default

2012-03-15 Thread Cameron Simpson
On 15Mar2012 09:28, Roy Smith r...@panix.com wrote:
| In article mailman.665.1331806024.3037.python-l...@python.org,
|  Robert Kern robert.k...@gmail.com wrote:
|  Yes. Not all type(default) types can be called with a string to produce a 
|  valid 
|  value. Note that type= is really a misnomer. argparse doesn't really want 
a 
|  type object there; it wants a converter function that takes a string to an 
|  object.
| 
| Orthogonal to my original suggestion, I agree that this is misnamed.  
| I'm +1 on the idea of renaming it to conversion= or something like that 
| (we'd need to keep type= around as a deprecated synonym for backwards 
| compatability).  It's really hard to get your head around type=open.

factory? Anyway, far too late to change this now!
-- 
Cameron Simpson c...@zip.com.au DoD#743
http://www.cskk.ezoshosting.com/cs/

all coders are created equal; that they are endowed with certain
unalienable rights, of these are beer, net connectivity, and the
pursuit of bugfixes...  - Gregory R Block
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a ConfigParser which keeps comments

2012-03-15 Thread Cameron Simpson
On 14Mar2012 13:13, Tim Chase python.l...@tim.thechases.com wrote:
| On 03/14/12 12:06, Terry Reedy wrote:
|  On 3/14/2012 6:07 AM, Gelonida N wrote:
|  Now I'm looking for a library, which behaves like config parser, but
|  with one minor difference.
| 
|  The write() mehtod should keep existing comments.
| 
|  Assuming that you have not overlooked anything, I would just subclass
|  ConfigParser with an altered write method.
| 
| It would require a lot more than that.  It would entail changing 
| the reading as well so that it preserved the comments as well as 
| the order of sections  keys, and a way of storing those 
| associated comments in sequence.  I looked into it a fair while 
| back and it was a LOT more work than I cared to do for minimal 
| gain.  I wimped out and just documented it with If you use the 
| ability to (re)write a configuration file, it will not keep any 
| comments or ordering from any original sources.

A low cost approach might be to patch the file instead of transcribing
the in-memory state. Not the same semantics, but it would not be too
hard to add a patch_config(filename, section, setting, value) that read
the old file and wrote a new one with an adjusted section, ignoring the
in-memory state (indeed, on that basis the siganture isn't a method but
a standalone function).

The logic is easy enough that I even wrote a shell script in 2004 to do
essentially this:

  https://bitbucket.org/cameron_simpson/css/src/ef42896872b5/bin/winclauseappend

One could imagine an efficient python implementation and a ConfigParser
subclass that patched the file if a setting got changed, or had a .patch
method to apply particular setting changes as desired.

Cheers,
-- 
Cameron Simpson c...@zip.com.au DoD#743
http://www.cskk.ezoshosting.com/cs/

From sci.physics:
t...@mailzone.com:
  The only problem is, how do you send a message from Earth to Mars
  instantly?  Does anyone have any ideas about where we can start?
John Baez b...@math.mit.edu:
  Just use a coordinate system in which the point at which the message is
  received has the same t coordinate as the point at which the message was sent.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a ConfigParser which keeps comments

2012-03-15 Thread Karim

Le 15/03/2012 03:48, Steven W. Orr a écrit :

On 3/14/2012 6:07 AM, Gelonida N wrote:

Hi,


At the moment I use ConfigParser
http://docs.python.org/library/configparser.html
for one of my applications.


Now I'm looking for a library, which behaves like config parser, but
with one minor difference.

The write() mehtod should keep existing comments.

Does anybody know or implement something like this or is there as
switrch, that I overlooked in hte documentaiton.




I use ConfigObj.



Sure configObj is a must...I use it too.

http://www.voidspace.org.uk/python/configobj.html

Cheers
Karim

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


Re: Python is readable

2012-03-15 Thread Michael Torrie
On 03/15/2012 01:40 PM, Kiuhnm wrote:
 Moreover, I think that
if (

):



 is not very readable anyway.

Sure but neither is
if ( \
 \
)




In other words, with or without the : if you format your if statements
in an unreadable way, it will be unreadable.  Nothing to do with
python's syntax at all.

Now,
if 
   
   :




isn't too bad for readability.  In other words the C-ism of putting the
IF predicate in parenthesis normally doesn't belong in python, though
there are cases when you need to enforce a certain operator precedence,
granted.

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


Re: Python is readable

2012-03-15 Thread Michael Torrie
On 03/15/2012 09:18 AM, Kiuhnm wrote:
  After early user testing without the colon, it was discovered that 
 the meaning of the indentation was unclear to beginners being taught the 
 first steps of programming. 
 
 The addition of the colon clarified it significantly: the colon somehow 
 draws attention to what follows and ties the phrases before and after it 
 together in just the right way.
 
 If that passage is correct, those studies don't say that adding the 
 colon increases the readability, but that it makes more sense to 
 beginners who don't even know what indentation is.

Seems to me that helping code to make more sense to a beginner is, by
definition, increasing readability.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is readable

2012-03-15 Thread Ben Finney
Kiuhnm kiuhnm03.4t.yahoo.it writes:

 Moreover, I think that
   if (
   
   ):
   
   
   
 is not very readable anyway.

I agree, and am glad PEP 8 has been updated to recommend an extra level
of indentation for continuation, to distinguish from the new block that
follows URL:http://www.python.org/dev/peps/pep-0008/#indentation.

-- 
 \   “From the moment I picked your book up until I laid it down I |
  `\was convulsed with laughter. Someday I intend reading it.” |
_o__)—Groucho Marx |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is readable

2012-03-15 Thread Arnaud Delobelle
On 15 March 2012 22:35, Ben Finney ben+pyt...@benfinney.id.au wrote:
 Kiuhnm kiuhnm03.4t.yahoo.it writes:

 Moreover, I think that
   if (
       
       ):
       
       
       
 is not very readable anyway.

 I agree, and am glad PEP 8 has been updated to recommend an extra level
 of indentation for continuation, to distinguish from the new block that
 follows URL:http://www.python.org/dev/peps/pep-0008/#indentation.

Personally I solve this by never writing if conditions that span more
than one line.  If the worst comes to the worst, I would write:

aptly_named_condition = (
very long condition
that goes over
plenty of lines
)
if aptly_named_condition:
do stuff

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


Re: Python is readable

2012-03-15 Thread Kiuhnm

On 3/15/2012 23:17, Michael Torrie wrote:

On 03/15/2012 09:18 AM, Kiuhnm wrote:

  After early user testing without the colon, it was discovered that
the meaning of the indentation was unclear to beginners being taught the
first steps of programming.

The addition of the colon clarified it significantly: the colon somehow
draws attention to what follows and ties the phrases before and after it
together in just the right way.

If that passage is correct, those studies don't say that adding the
colon increases the readability, but that it makes more sense to
beginners who don't even know what indentation is.


Seems to me that helping code to make more sense to a beginner is, by
definition, increasing readability.


Pick up two math books about the same topic but on two different levels 
(e.g. under-graduated and graduated). If you compare the proofs you'll 
see that those in the higher-level book are almost always sketched. Why 
is that? Because they're more readable for a mature reader. But they're 
almost incomprehensible to a beginner.
As another example, why do people use jargon? Because that makes 
communication more efficient. And yet that frustrate beginners.
So, no, I can't agree with you. There are too many situations where a 
steep learning curve pays off in the long run. Making that curve too 
shallow may help beginners but damage experienced users.
Is functional programming code more readable than imperative code? Ask a 
beginner and you'll receive a resounding no. Ask an experienced coder 
and he will probably say it depends. If he says yes, always he is a 
just a lisp fanatic :)


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


Re: Python is readable

2012-03-15 Thread Kiuhnm

On 3/16/2012 0:00, Arnaud Delobelle wrote:

On 15 March 2012 22:35, Ben Finneyben+pyt...@benfinney.id.au  wrote:

Kiuhnmkiuhnm03.4t.yahoo.it  writes:


Moreover, I think that
   if (
   
   ):
   
   
   
is not very readable anyway.


I agree, and am glad PEP 8 has been updated to recommend an extra level
of indentation for continuation, to distinguish from the new block that
followsURL:http://www.python.org/dev/peps/pep-0008/#indentation.


Personally I solve this by never writing if conditions that span more
than one line.  If the worst comes to the worst, I would write:

aptly_named_condition = (
 very long condition
 that goes over
 plenty of lines
)
if aptly_named_condition:
 do stuff


Will I be able to use extra indentation in Python code?
For instance,

  res = and(or(cond1,
   cond2),
cond3,
or(and(cond4,
   cond5,
   cond6),
   and(cond7,
   cond8)))

I like it because it reads like a tree.

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


Re: Python is readable

2012-03-15 Thread Steven D'Aprano
On Fri, 16 Mar 2012 01:48:09 +1100, Chris Angelico wrote:

 On Fri, Mar 16, 2012 at 1:30 AM, Kiuhnm
 kiuhnm03.4t.yahoo...@mail.python.org wrote:
 Sorry, but I can't see how it would make it harder for humans to
 understand. Are there particular situations you're referring to?
 
 In a trivial example, it's mostly just noise:
 
 if a == b# who needs the colon?
 print(c)

The reader, for the same reason that above you wrote:

In a trivial example, it's mostly just noise COLON

and indeed I too used a colon for the same reason. It ties the lead 
sentence to the following block without ending the sentence, but still 
introducing a new grouping or clause.

It is *remarkable* how people take the colon for granted. It is so simple 
and so obvious that they use it in their own writing often without 
thinking about it, but because it is not strictly necessary to avoid 
ambiguity in the grammar, they fool themselves into thinking that it is 
just noise or pointless. It is not noise, it is a hint to the reader.

Again, applying to both computer languages and natural languages, leaving 
out punctuation (either in the grammar, or just out of laziness) is doing 
a great disservice to the reader. The time the writer saves by not 
inserting punctuation is lost a million times for the reader (we read 
text and code thousands of times more than we write it, and there are 
thousands more readers than writers). Leaving out punctuation is a real 
pessimation: an example of being penny wise and pound foolish.



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


Re: Python is readable

2012-03-15 Thread Ben Finney
Arnaud Delobelle arno...@gmail.com writes:

 On 15 March 2012 22:35, Ben Finney ben+pyt...@benfinney.id.au wrote:
  I agree, and am glad PEP 8 has been updated to recommend an extra
  level of indentation for continuation, to distinguish from the new
  block that follows
  URL:http://www.python.org/dev/peps/pep-0008/#indentation.

 Personally I solve this by never writing if conditions that span more
 than one line.

The admonition applies not only to ‘if’ conditions, but also to ‘while’,
‘with’, ‘for’, etc.; and also to bracketing constructs like function
calls, literal lists/dicts/sets, etc. In a single statement, the
indentation for continuation lines should be indented two levels, so
that they don't look so much like a new block of statements.

-- 
 \   “If you do not trust the source do not use this program.” |
  `\—Microsoft Vista security dialogue |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is readable

2012-03-15 Thread Mark Lawrence

On 15/03/2012 23:46, Kiuhnm wrote:

On 3/16/2012 0:00, Arnaud Delobelle wrote:

On 15 March 2012 22:35, Ben Finneyben+pyt...@benfinney.id.au wrote:

Kiuhnmkiuhnm03.4t.yahoo.it writes:


Moreover, I think that
if (

):



is not very readable anyway.


I agree, and am glad PEP 8 has been updated to recommend an extra level
of indentation for continuation, to distinguish from the new block that
followsURL:http://www.python.org/dev/peps/pep-0008/#indentation.


Personally I solve this by never writing if conditions that span more
than one line. If the worst comes to the worst, I would write:

aptly_named_condition = (
very long condition
that goes over
plenty of lines
)
if aptly_named_condition:
do stuff


Will I be able to use extra indentation in Python code?
For instance,

res = and(or(cond1,
cond2),
cond3,
or(and(cond4,
cond5,
cond6),
and(cond7,
cond8)))

I like it because it reads like a tree.

Kiuhnm


Why not find out for yourself by slapping the code into an interactive 
Python interpreter and seeing what the result is?


--
Cheers.

Mark Lawrence.

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


Re: Python is readable

2012-03-15 Thread Steven D'Aprano
On Fri, 16 Mar 2012 00:46:35 +0100, Kiuhnm wrote:

 On 3/16/2012 0:00, Arnaud Delobelle wrote:
 On 15 March 2012 22:35, Ben Finneyben+pyt...@benfinney.id.au  wrote:
 Kiuhnmkiuhnm03.4t.yahoo.it  writes:

 Moreover, I think that
if (

):



 is not very readable anyway.

 I agree, and am glad PEP 8 has been updated to recommend an extra
 level of indentation for continuation, to distinguish from the new
 block that
 followsURL:http://www.python.org/dev/peps/pep-0008/#indentation.

 Personally I solve this by never writing if conditions that span more
 than one line.  If the worst comes to the worst, I would write:

 aptly_named_condition = (
  very long condition
  that goes over
  plenty of lines
 )
 if aptly_named_condition:
  do stuff
 
 Will I be able to use extra indentation in Python code? For instance,
 
res = and(or(cond1,
 cond2),
  cond3,
  or(and(cond4,
 cond5,
 cond6),
 and(cond7,
 cond8)))

Not that exact example, because `and` and `or` are operators, not 
functions and you will get a syntax error. Python uses infix notation, 
not prefix or postfix:

x and y# yes
and(x, y)  # no
x y and# no


But in general, yes, you can use whatever indentation you like inside a 
line-continuation bracket:

py x = [
... 1, 2, 3,
... 4, 5, 6,
... 7, 8, 9,
... 10, 11, 12,
...   13, 14, 15
... ]
py x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]


Indentation is only syntactically significant in blocks and statements.


 
 I like it because it reads like a tree.

Funny. I dislike it because it is a tree on its side.



-- 
Steven

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


Re: Is there a ConfigParser which keeps comments

2012-03-15 Thread Gelonida N
On 03/15/2012 10:42 PM, Cameron Simpson wrote:
 On 14Mar2012 13:13, Tim Chase python.l...@tim.thechases.com wrote:
 | On 03/14/12 12:06, Terry Reedy wrote:
 |  On 3/14/2012 6:07 AM, Gelonida N wrote:
 |  Now I'm looking for a library, which behaves like config parser, but
 |  with one minor difference.
 | 
 |  The write() mehtod should keep existing comments.
 | 
 |  Assuming that you have not overlooked anything, I would just subclass
 |  ConfigParser with an altered write method.
 | 
 | It would require a lot more than that.  It would entail changing 
 | the reading as well so that it preserved the comments as well as 
 | the order of sections  keys, and a way of storing those 
 | associated comments in sequence.  I looked into it a fair while 
 | back and it was a LOT more work than I cared to do for minimal 
 | gain.  I wimped out and just documented it with If you use the 
 | ability to (re)write a configuration file, it will not keep any 
 | comments or ordering from any original sources.
 
 A low cost approach might be to patch the file instead of transcribing
 the in-memory state. Not the same semantics, but it would not be too
 hard to add a patch_config(filename, section, setting, value) that read
 the old file and wrote a new one with an adjusted section, ignoring the
 in-memory state (indeed, on that basis the siganture isn't a method but
 a standalone function).
 
 The logic is easy enough that I even wrote a shell script in 2004 to do
 essentially this:
 
   
 https://bitbucket.org/cameron_simpson/css/src/ef42896872b5/bin/winclauseappend
 
 One could imagine an efficient python implementation and a ConfigParser
 subclass that patched the file if a setting got changed, or had a .patch
 method to apply particular setting changes as desired.
 

Agreed, patching is simpler than parsing the file and keeping all the
comment info in the config object.

I will also look at  ConfigObj as suggested by Steven and Karim

If this does what I want, then it's probably less effort to use this
library than patching Configparser.


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


Re: Python is readable

2012-03-15 Thread Steven D'Aprano
On Thu, 15 Mar 2012 00:34:47 +0100, Kiuhnm wrote:

 I've just started to read
The Quick Python Book (2nd ed.)

Is this the one?

http://manning.com/ceder/


 The author claims that Python code is more readable than Perl code and
 provides this example:
 
 --- Perl ---
 sub pairwise_sum {
  my($arg1, $arg2) = @_;
  my(@result) = ();
  @list1 = @$arg1;
  @list2 = @$arg2;

I don't understand the reason for $arg1 and $arg2. Is there some reason 
why the code couldn't do this instead?

   my(@list1, @list2) = @_;


  for($i=0; $i  length(@list1); $i++) {
  push(@result, $list1[$i] + $list2[$i]);
  }
  return(\@result);
 }
 
 --- Python ---
 def pairwise_sum(list1, list2):
  result = []
  for i in range(len(list1)):
  result.append(list1[i] + list2[i])
  return result
 --- ---
 
 It's quite clear that he knows little about Perl.

On the contrary -- it is quite clear that you are missing the point of 
the comparison, which is not to compare the most idiomatic Perl with the 
most idiomatic Python, but to make a direct comparison of syntax for the 
purpose of teaching beginners.

The problem with idiomatic comparisons is that they often don't give you 
a feel for the overall language syntax. Instead they end up comparing 
built-ins. For example, here is how I would write the above pairwise 
addition using idiomatic RPL, the Forth-like programming language used on 
some Hewlett-Packard scientific calculators:

ADD

That's it. One word. Would you conclude from this that RPL is easier to 
read and write than Python? I can tell you that it is not, and I *like* 
stack-based languages that use reverse Polish Notation.


 Here's what I would've written:
 
 sub pairwise_sum {
  my ($list1, $list2) = @_;
  my @result;
  push @result, $list1-[$_] + $list2-[$_] for (0..@$list1-1);
  \@result;
 }
 
 Having said that, the Python code is still more readable, so there's no
 need to misrepresent Perl that way.

Speaking as somebody who doesn't know Perl, I think that your version 
would do a great disservice to Perl. Your version is shorter, but 
conciseness is often in opposition to readability. Without the author's 
version above, and the function name, I would have literally NO IDEA what 
your version does. It is virtually pure line-noise. I know enough Perl to 
guess that @result might be an array, and so guess that push pushes a 
value onto the array, but the rest might as well be written in Martian. 
Or APL.

The author's version above, which you denigrate, is *much* more 
understandable than your more idiomatic Perl, especially since I can 
compare it feature to feature with the Python code.

Far from misrepresenting Perl, he has gone out of his way to show Perl in 
the best possible light. Idiomatic Perl code, written by experts, is even 
more incomprehensible and unreadable to non-Perl hackers than his example.


 Now I'm wondering whether the author will show me good or bad Python
 code throughout the book. Should I keep reading?

From what you have show, and the sample chapters on the link above, I am 
impressed. The author is aiming to teach basic concepts and impart 
*understanding* rather than just force-feed the reader idioms which would 
be incomprehensible to them. Vern Cedar (the author) is an actual 
professional teacher, and from the samples I have seen, he knows what he 
is doing.


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


Re: Is it technically possible to give Python option of naming process of running script?

2012-03-15 Thread Dave Angel

On 03/15/2012 02:39 PM, Grant Edwards wrote:

On 2012-03-15, Dave Angeld...@davea.name  wrote:

On 03/15/2012 03:26 AM, xliiv wrote:

Like the topic.. .
I use Python a lot, both Windows and Linux, and it's little weird to have many 
python process without fast distinction which is what.

I did google, I've played with Exemaker (it works perfect, but not py3) and 
i've seen questions on Stackoverflow.
The thing I mean is a build feature of python to give such a name. Not 3rd part 
or etc. like Grant Edwards said. Is it possible?

How about simply using cp to copy the python executable, run chmod +x on
it, and run that one?  Then ps would list it as the new name, not as python.

That's rather a waste of memory.  Better to use a link.  That way the
executable can still be shared by multiple programs and won't be
duplicated in memory.


i tried it on /usr/bin/python2.7but I see no reason the same
approach won't work on 3.x  Note, I copied it to a new name in the same
directory, which may be important.  or not.

Seems like an awfully obtuse way of doing things -- I don't really
want to have 15 different copies of Python (or even links), and it
requires root privleges every time you want to run a Python program
with the correct name.



Good point about using a link.  I was trying to make something that 
would probably also work in Windows. As for the needing of root 
privileges, that's only for those programs you need to be able to 
identify with ps, and only one time for each.


Anyway, it's a response to a specific need, which I don't share, and it 
was my second suggestion, not first.




--

DaveA

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


Re: Python is readable

2012-03-15 Thread Steven D'Aprano
On Thu, 15 Mar 2012 20:54:30 +, Arnaud Delobelle wrote:

 On 15 March 2012 00:27, Chris Angelico ros...@gmail.com wrote:
 On Thu, Mar 15, 2012 at 10:54 AM, Arnaud Delobelle arno...@gmail.com
 wrote:
 I don't know this book and there may be a pedagogical reason for the
 implementation you quote, but pairwise_sum is probably better
 implemented in Python 3.X as:

 def pairwise_sum(list1, list2):
    return [x1 + x2 for x1, x2 in zip(list1, list2)]

 Okay, here's something for debate.

 Should the readability of a language be gauged on the basis of its
 standard library, or should you be comparing actual code?
 
 But here's the code posted by the OP:
 
 --- Python ---
 def pairwise_sum(list1, list2):
result = []
for i in range(len(list1)):
result.append(list1[i] + list2[i])
return result
 --- ---
 
 The code I posted uses one builtin function (zip), the code posted by
 the OP uses two (range and len).  Neither uses the standard library.


For beginners, code using range and len is MUCH easier to understand than 
code using zip. len is obviously short for length, and range (at least in 
the one-argument version) is simple to explain. But zip? To understand 
zip, you need to have a good concept of iteration in your head. When 
writing for beginners, you can't assume that.

For beginners, the most idiomatic code is not necessarily the simplest 
code. I would never start beginners with a list comprehension:

result = [a+b for a,b in zip(list1, list2)]

which is likely to be just incomprehensible jargon. You need to 
understand the syntax, which may not be obvious even to people with a 
mathematics background. (List comps are copied from Haskell, where they 
derive their syntax from mathematicians' set notation.) You need to 
understand zip, which requires having a good mental model of element-wise 
iteration. Although it is longer and less idiomatic, the Python1.5-ish 

result = []
for i in range(len(list1)):
result.append(list1[i] + list2[i])

is likely to be simpler to understand.

The downside is that experienced programmers may roll their eyes at how 
you are dumbing down the code, or worse, accusing you of deliberately 
misrepresenting the language.



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


Re: Python is readable

2012-03-15 Thread Mark Lawrence

On 16/03/2012 01:53, Steven D'Aprano wrote:

On Thu, 15 Mar 2012 00:34:47 +0100, Kiuhnm wrote:


I've just started to read
The Quick Python Book (2nd ed.)


Is this the one?

http://manning.com/ceder/



The author claims that Python code is more readable than Perl code and
provides this example:

--- Perl ---
sub pairwise_sum {
  my($arg1, $arg2) = @_;
  my(@result) = ();
  @list1 = @$arg1;
  @list2 = @$arg2;


I don't understand the reason for $arg1 and $arg2. Is there some reason
why the code couldn't do this instead?

my(@list1, @list2) = @_;



  for($i=0; $i  length(@list1); $i++) {
  push(@result, $list1[$i] + $list2[$i]);
  }
  return(\@result);
}

--- Python ---
def pairwise_sum(list1, list2):
  result = []
  for i in range(len(list1)):
  result.append(list1[i] + list2[i])
  return result
--- ---

It's quite clear that he knows little about Perl.


On the contrary -- it is quite clear that you are missing the point of
the comparison, which is not to compare the most idiomatic Perl with the
most idiomatic Python, but to make a direct comparison of syntax for the
purpose of teaching beginners.

The problem with idiomatic comparisons is that they often don't give you
a feel for the overall language syntax. Instead they end up comparing
built-ins. For example, here is how I would write the above pairwise
addition using idiomatic RPL, the Forth-like programming language used on
some Hewlett-Packard scientific calculators:

ADD

That's it. One word. Would you conclude from this that RPL is easier to
read and write than Python? I can tell you that it is not, and I *like*
stack-based languages that use reverse Polish Notation.



Here's what I would've written:

sub pairwise_sum {
  my ($list1, $list2) = @_;
  my @result;
  push @result, $list1-[$_] + $list2-[$_] for (0..@$list1-1);
  \@result;
}

Having said that, the Python code is still more readable, so there's no
need to misrepresent Perl that way.


Speaking as somebody who doesn't know Perl, I think that your version
would do a great disservice to Perl. Your version is shorter, but
conciseness is often in opposition to readability. Without the author's
version above, and the function name, I would have literally NO IDEA what
your version does. It is virtually pure line-noise. I know enough Perl to
guess that @result might be an array, and so guess that push pushes a
value onto the array, but the rest might as well be written in Martian.
Or APL.

The author's version above, which you denigrate, is *much* more
understandable than your more idiomatic Perl, especially since I can
compare it feature to feature with the Python code.

Far from misrepresenting Perl, he has gone out of his way to show Perl in
the best possible light. Idiomatic Perl code, written by experts, is even
more incomprehensible and unreadable to non-Perl hackers than his example.



Now I'm wondering whether the author will show me good or bad Python
code throughout the book. Should I keep reading?



From what you have show, and the sample chapters on the link above, I am

impressed. The author is aiming to teach basic concepts and impart
*understanding* rather than just force-feed the reader idioms which would
be incomprehensible to them. Vern Cedar (the author) is an actual
professional teacher, and from the samples I have seen, he knows what he
is doing.




Well put Sir.  And (seriously) when making your comments you show the 
killer instincts of a great bowler in an Ashes Test Match, now could 
there be anything more important in life or showing greater esteem than 
that?


--
Cheers.

Mark Lawrence.

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


Python simulate browser activity

2012-03-15 Thread choi2k
Hi, everyone

I am trying to write a small application using python but I am not
sure whether it is possible to do so..
The application aims to simulate user activity including visit a
website and perform some interactive actions (click on the menu,
submit a form, redirect to another pages...etc)
I have found some libraries / plugins which aims to simulate browser
activity but ... none of them support AJAX request and/or running
javascript.

Here is one of the simple tasks which I would like to do using the
application:
1. simulate the user activity, visit the website (https://
www.abc.com)
2. find out the target element by id (submitBtn) and simulate mouse
click on the item.
3. perform some javascript functions which invoked by click event from
step 2. ( the function is bind to the item by jquery)
4. post ajax request using javascript and if the page has been
redirected, load the new page content

Is it possible to do so?

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


Re: Python simulate browser activity

2012-03-15 Thread Chris Rebert
On Thu, Mar 15, 2012 at 7:23 PM, choi2k rex.0...@gmail.com wrote:
 Hi, everyone

 I am trying to write a small application using python but I am not
 sure whether it is possible to do so..
 The application aims to simulate user activity including visit a
 website and perform some interactive actions (click on the menu,
 submit a form, redirect to another pages...etc)
 I have found some libraries / plugins which aims to simulate browser
 activity but ... none of them support AJAX request and/or running
 javascript.

Did you look at Selenium?
http://seleniumhq.org/

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


Re: Python is readable

2012-03-15 Thread Chris Angelico
On Fri, Mar 16, 2012 at 10:52 AM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 On Fri, 16 Mar 2012 01:48:09 +1100, Chris Angelico wrote:

 In a trivial example, it's mostly just noise:

 if a == b    # who needs the colon?
     print(c)

 The reader, for the same reason that above you wrote:

 In a trivial example, it's mostly just noise COLON

 and indeed I too used a colon for the same reason. It ties the lead
 sentence to the following block without ending the sentence, but still
 introducing a new grouping or clause.

Yep. As everyone who communicates on the internet knows, punctuation
can often be omitted without introducing ambiguity. That doesn't mean
it *should* be omitted. NOT TELEGRAMS TODAY STOP

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


Re: Is it technically possible to give Python option of naming process of running script?

2012-03-15 Thread Chris Angelico
On Fri, Mar 16, 2012 at 5:39 AM, Grant Edwards invalid@invalid.invalid wrote:
 Seems like an awfully obtuse way of doing things -- I don't really
 want to have 15 different copies of Python (or even links), and it
 requires root privleges every time you want to run a Python program
 with the correct name.

Why do you need root? Can't you copy / link into your own home directory?

I may have misunderstood something here.

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


Re: Python simulate browser activity

2012-03-15 Thread Jerry Hill
On Thu, Mar 15, 2012 at 10:54 PM, Chris Rebert c...@rebertia.com wrote:
 On Thu, Mar 15, 2012 at 7:23 PM, choi2k rex.0...@gmail.com wrote:
 The application aims to simulate user activity including visit a
 website and perform some interactive actions (click on the menu,
 submit a form, redirect to another pages...etc)

 Did you look at Selenium?
 http://seleniumhq.org/

You might also be interested in Sikuli (http://sikuli.org/), which
uses Jython to write scripts to automate other programs using
screenshots.  It's pretty neat if you need to automate a GUI that is
otherwise difficult to deal with.

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


Re: Python is readable

2012-03-15 Thread Steven D'Aprano
On Fri, 16 Mar 2012 00:32:52 +0100, Kiuhnm wrote:

 Pick up two math books about the same topic but on two different levels
 (e.g. under-graduated and graduated). If you compare the proofs you'll
 see that those in the higher-level book are almost always sketched. Why
 is that? Because they're more readable for a mature reader.

No. They're not more readable. They simply have less to read (per proof), 
or another way of putting it, you can fit more of the good stuff that the 
experienced reader wants (yes yes, I know about the associative law, get 
to the part where you prove the Goldbach conjecture...) in the same 
amount of space. The text is compressed by leaving out the parts that an 
experienced reader can infer from her knowledge of the domain.

Since an expert can infer meaning more quickly than they can read the 
actual words, this is a big win for efficiency. But the text is not more 
readable, there's just less to read for a given result. The same amount, 
or even more, brain processing occurs. It just happens in a different 
part of the brain.

In Python terms, it's analogous to moving something out of a pure-Python
O(log n) binary tree into a fast O(n) linear array written in C. Until 
the concepts get complex enough, it is faster for the expert to infer 
meaning than to read explicitly, even though technically more work is 
probably being done.


Experts often find pedagogical texts harder to read because it seems 
dumbed down. It's as if they are reading text like this:

The cat, which is a small animal with fur known for being 
aloof and yet attractive to many people, sat on the mat, 
which is like a rug or blanket except thicker, while Jack, 
a small male child, and Jill, a young female child, ran, 
that is to say travelled quickly by lifting their feet and 
moving forward in such a fashion that sometimes both feet 
are in the air simultaneously, up the hill, a moderately-
sized elevation of land smaller than a mountain.


It gets painful after a while because, as an expert, you can interpret 
the subtext quicker than you can read the actual words. But when teaching 
non-experts, you can't expect the reader to interpret the subtext quickly 
or at all. Which is more readable, that is to say, more comprehensible?

The wix sat on the zaj, while Megf and Parz vev up the leff.

Lacking any domain knowledge, the above carries virtually no information 
at all. We know that wixes can sit on things, and that's about it.

Contrast this:

The wix, which is a small animal with fur known for being 
aloof and yet attractive to many people, sat on the zaj, 
which is like a rug or blanket except thicker, while Megf, 
a small male child, and Parz, a young female child, vev, 
that is to say travelled quickly by lifting their feet and 
moving forward in such a fashion that sometimes both feet 
are in the air simultaneously, up the leff, a moderately-
sized elevation of land smaller than a mountain.

Despite having about 8 times as much content, and being one long run-on 
sentence, this version is far more comprehensible. (In practice, I 
wouldn't define terms in the sentence I was using them in this fashion. 
Or at least not more than one per sentence. Very long sentences have 
their own readability costs.)

When people talk about readability, they normally mean to ask how much 
mental effort is needed to interpret the meaning of the text, not how 
much time does it take to pass your eyes over the characters. In other 
words they are actually talking about comprehensibility.

Well obviously that depends on who is doing the reading. To somebody in 
the know, meaning can be incredibly compressed. You can crack up Monty 
Python fans with just two words: Norwegian Blue. To those not in the 
know, that's incomprehensible.

When speaking about programming languages, the reader who is judging 
readability is assumed to be:

- somebody with a good grasp of natural language, normally 
  English, and capable of understanding sentences containing
  loops and conditionals such as

soak and rinse the beans three times
scrub the potatoes until the dirt is gone
if the tap is dripping, replace the washer

- possessing an intuitive understanding of such concepts as 
  is-a and has-a (Fido is a dog, Fido has a tail);

- possessing a simple knowledge of basic arithmetic and logic;

- able to intuit the meaning of programming concepts if they
  match simple natural language concepts (e.g. print, delete, 
  but not necessarily import, delegate, and certainly not 
  currying, closures, monads);

- but not familiar with the programming language, its data 
  model, or the details of its functions and commands;

- and of average intelligence, neither a dummy nor a genius. 

(Despite the proliferation of books with titles like Programming For 
Utter Morans, they aren't actually written for dummies.)

To judge the readability of a language, we have to put 

[issue14278] email.utils.localtime throws exception if time.daylight is False

2012-03-15 Thread R. David Murray

Changes by R. David Murray rdmur...@bitdance.com:


--
assignee:  - r.david.murray
resolution:  - fixed
stage:  - committed/rejected
type:  - behavior

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue14278
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue14278] email.utils.localtime throws exception if time.daylight is False

2012-03-15 Thread R. David Murray

R. David Murray rdmur...@bitdance.com added the comment:

Fixed in the email6 feature branch.  Thanks Brian.

--
status: open - closed

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue14278
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue4199] add shorthand global and nonlocal statements

2012-03-15 Thread Raymond Hettinger

Raymond Hettinger raymond.hettin...@gmail.com added the comment:

+1 on the feature as described in the PEP.

--
nosy: +rhettinger

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue4199
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue14309] Deprecate time.clock()

2012-03-15 Thread Marc-Andre Lemburg

Marc-Andre Lemburg m...@egenix.com added the comment:

STINNER Victor wrote:
 
 New submission from STINNER Victor victor.stin...@gmail.com:
 
 Python 3.3 has 3 functions to get time:
 
  - time.clock()
  - time.steady()
  - time.time()
 
 Antoine Pitrou suggested to deprecated time.clock() in msg120149 (issue 
 #10278).
 
 The problem is time.clock(), since it does two wildly different things
 depending on the OS. I would suggest to deprecate time.clock() at the same 
 time as we add time.wallclock(). For the Unix-specific definition of 
 time.clock(), there is already os.times() (which gives even richer 
 information).
 
 (time.wallclock was the old name of time.steady)

Strong -1 on this idea.

time.clock() has been in use for ages in many many scripts. We don't
want to carelessly break all those.

--
nosy: +lemburg

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue14309
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12758] time.time() returns local time instead of UTC

2012-03-15 Thread Roundup Robot

Roundup Robot devn...@psf.upfronthosting.co.za added the comment:

New changeset 1559a82a3529 by R David Murray in branch '2.7':
#12758: removing confusing mention of UTC from time.time description
http://hg.python.org/cpython/rev/1559a82a3529

New changeset 5615d6b91b53 by R David Murray in branch '3.2':
#12758: removing confusing mention of UTC from time.time description
http://hg.python.org/cpython/rev/5615d6b91b53

New changeset f18767bb66ba by R David Murray in branch 'default':
Merge #12758: removing confusing mention of UTC from time.time description
http://hg.python.org/cpython/rev/f18767bb66ba

--
nosy: +python-dev

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12758
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue14127] add st_*time_ns fileds to os.stat(), add ns keyword to os.*utime*(), os.*utimens*() expects a number of nanoseconds

2012-03-15 Thread Larry Hastings

Larry Hastings la...@hastings.org added the comment:

My revised patch, incorporating changes suggested by Antoine and Guido.

--
Added file: http://bugs.python.org/file24859/larry.st_mtime_ns.patch.2.txt

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue14127
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12758] time.time() returns local time instead of UTC

2012-03-15 Thread R. David Murray

R. David Murray rdmur...@bitdance.com added the comment:

Thanks, Dylan.

--
nosy: +r.david.murray
resolution:  - fixed
stage: needs patch - committed/rejected
status: open - closed
type:  - behavior

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12758
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue14312] Convert PEP 7 to reStructuredText for readability purposes

2012-03-15 Thread Georg Brandl

New submission from Georg Brandl ge...@python.org:

Yes, who not.  Applied in 5d6ae5e01df6.

--
nosy: +georg.brandl
resolution:  - fixed
status: open - closed

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue14312
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue14312] Convert PEP 7 to reStructuredText for readability purposes

2012-03-15 Thread Georg Brandl

Georg Brandl ge...@python.org added the comment:

Yes, why not. Applied in c1fd4a5af1c5.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue14312
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue14312] Convert PEP 7 to reStructuredText for readability purposes

2012-03-15 Thread Georg Brandl

Changes by Georg Brandl ge...@python.org:


--
Removed message: http://bugs.python.org/msg155870

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue14312
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



  1   2   3   >