Re: allow line break at operators

2011-08-12 Thread Chris Angelico
On Fri, Aug 12, 2011 at 2:40 AM, Steven D'Aprano
 wrote:
> Please be careful about conflating significant indentation with significant
> whitespace. Many languages have significant whitespace:
>
> foo bar
>
> is rarely the same thing as
>
> foobar
>
> but is the same as
>
> foo           bar
>
> Python is no different.
>

Of course. But most languages derived from C have a single lexer token
"whitespace". That one token is significant, but these are all the
same:

foo bar
foo   bar
foo
bar
foo/* this one wasn't originally the same*/bar

Python handles differently source files that differ only in
whitespace. It's not only indentation; newlines are whitespace too,
and they're significant. In C-derived languages, it's only
presence-or-absence.

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


Re: String concatenation - which is the fastest way ?

2011-08-12 Thread przemolicc
On Thu, Aug 11, 2011 at 02:38:32PM -0700, SigmundV wrote:
> When I saw the headline I thought "oh no, not string concatenation
> again... we have had scores of these thread before...", but this is a
> rather interesting problem. The OP says he's not a database
> developer,  but why is he then fiddling with internal database
> operations? Wouldn't it be better to go back to the database
> developers and have them look into parallel processing. I'm sure that
> Oracle databases can do parallel processing by now...

:-)
Good question but I try to explain what motivates me to do it.
First reason (I think the most important :-) ) is that I want to learn
something new - I am new to python (I am unix/storage sysadmin but with 
programming
background so python was a natural choice for more complicated
sysadmin tasks).
Another reason is that our server (and I am responsible for it) has
many, many but slow cores (as I had written before). It means that
parallelization of operations is obvious - the developer is not keen
to spent much time on it (she is busy) - and for me this is something new
(among some boring daily tasks ... ;-) ) and fresh :-)
Another intention is to get some more knowledge about parallelization:
how to divide some task into subtasks, what is the most optimal way to do it, 
etc
And the last reason is that I love performance tuning :-)

Regards
Przemyslaw Bak (przemol)




















































Zmyslowa bielizna? U nas ja znajdziesz!
http://linkint.pl/f29fe
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-12 Thread Chris Angelico
On Fri, Aug 12, 2011 at 7:34 AM, Seebs  wrote:
> If Python with braces wouldn't be Python at all, why on earth does the
> language even exist?

Every language has its philosophy. Python, as conceived by Guido van
Rossum, is a language which (guys, correct me where I'm wrong
please!):

* Eschews unnecessary syntactic salt
* Has "batteries included"
* Has a clean and readable syntax

To achieve this, Python:

* Uses indentation and other whitespace as structural elements (rather
than semicolons, braces, etc)
* Has a large standard library and an enormous PyPI collection
* Uses keywords (and, or, not, if/else) rather than symbols (&, |, !,
?:) for common tasks

Etcetera. These are the philosophical decisions made by GvR and the
Python community, and these define Python's syntax. If you go against
these, you could make something that compiles down to Python's byte
code; in fact, I'd say you could make something that produces a .pyc
file and then hands it to the regular Python interpreter for
execution. Is it Python? No, no more than NetREXX is Java just because
it can make a .class file. It's a different language.

Pike is very similar to Python in underlying structure. You can pass
lists and dictionaries (called arrays and mappings) around as
first-class objects, you can reference objects in multiple places, you
can work with huge integers comfortably. But they're different in
philosophy. Pike's purpose is primarily zero-downtime servers; I can
(and do on a daily basis) update parts of the code of a running
program, without disconnecting clients. Python doesn't do this, and to
make Python do this would violate a lot of its simplicities and
underlying referencings. It can be done without modifying the
interpreter, but it's never been designed in. If you want that
feature, you go to Pike; if you want Python's syntax, you go to
Python.

I hope I make myself clear, Josephine?

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


Re: generate and send mail with python: tutorial

2011-08-12 Thread maedox
On Friday, August 12, 2011 8:51:33 AM UTC+2, Dennis Lee Bieber wrote:
> On Thu, 11 Aug 2011 08:07:09 -0700 (PDT), aspineux 
> declaimed the following in gmane.comp.python.general:
> 
> > Hi I have written a tutorial about how to generate and send emails
> > with python.
> 
>   Is that really such a difficult task?
> 
>   Okay, I didn't really use Python for the entire creation of the
> message... But my first real Python program (using 1.4 or 1.5, whatever
> was included in the first "Programming Python" disk, for AmigaOS) was a
> rudimentary outgoing SMTPd which had to parse headers from  message
> files "queued" by an ARexx script from an Amiga version of ELM, then
> handshake with the ISP SMTPd to relay the message onward. It took less
> than a week after buying the book that I had this ARexx/Python hybrid
> working -- and it worked better than either C-language programs I'd
> downloaded (at that period of time, Amiga email programs ONLY read from
> local spool and queued to local spool; separate programs had to be used
> to read POP3 and send SMTP... My first SMTP utility presumed 1) direct
> connection to destination address, 2) created an email file for each
> address -- problem: if a destination did not have a receiving SMTPd [ie,
> one needed to do an MX lookup instead] it would hang trying to send that
> message, and never process others... The second program used ISP relay
> -- but it only parsed the "TO:" header, and thereby failed to handshake
> CC and BCC destinations)
> -- 
>   Wulfraed Dennis Lee Bieber AF6VN
> [email protected]://wlfraed.home.netcom.com/

Nice story bro...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Processing a large string

2011-08-12 Thread Peter Otten
goldtech wrote:

> Hi,
> 
> Say I have a very big string with a pattern like:
> 
> akakksssk3dhdhdhdbddb3dkdkdkddk3dmdmdmd3dkdkdkdk3asnsn.
> 
> I want to split the sting into separate parts on the "3" and process
> each part separately. I might run into memory limitations if I use
> "split" and get a big array(?)  I wondered if there's a way I could
> read (stream?) the string from start to finish and read what's
> delimited by the "3" into a variable, process the smaller string
> variable then append/build a new string with the processed data?
> 
> Would I loop it and read it char by char till a "3"...? Or?

You can read the file in chunks:

from functools import partial

def read_chunks(instream, chunksize=None):
if chunksize is None:
chunksize = 2**20
return iter(partial(instream.read, chunksize), "")

def split_file(instream, delimiter, chunksize=None):
leftover = ""
chunk = None
for chunk in read_chunks(instream):
chunk = leftover + chunk
parts = chunk.split(delimiter)
leftover = parts.pop()
for part in parts:
yield part
if leftover or chunk is None or chunk.endswith(delimiter):
yield leftover

I hope I got the corner cases right.

PS: This has come up before, but I couldn't find the relevant threads...

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


Re: allow line break at operators

2011-08-12 Thread Ben Finney
Seebs  writes:

> On 2011-08-11, Ben Finney  wrote:
> > You're welcome to attempt to demonstrate the superiority of some
> > other Python-with-braces, but it will (a) be un-Pythonic, and (b) be
> > unlikely to gain the efforts of people who don't think what you're
> > addressing is a problem.
>
> I am pretty sure Python is a pretty nice language. However, the
> indentation thing has screwed me a few times. Furthermore, I know
> people who like Python a great deal and acknowledge, without much
> difficulty, that the indentation thing has caused problems or
> incompatibilities for them.

Yes. It's caused problems for me too, so I'm not going to deny that.

This is different from saying “indentation as block structure” is a
problem; that statement is what I disagree with, and what I think most
respondents who disagree with you are objecting to.

> So when I see people deny that it is at all a problem, or that there
> are any possible shortcomings to it, I infer that they have some
> compelling reason to deny the existence of a thing which is reliably
> and easily observed.

I don't see anyone making the denials you're referring to there. If I
did, you would have my support in considering those denials mistaken.

Likewise, “end of line as end of statement” has caused me and many
others problems. I'd go so far as to say that any Python programmer for
whom that's not true has not done any significant Python programming.
That doesn't make “end of line as end of statement” a problem.

If a language feature is beneficial in far greater proportion to the
inconveniences of that feature, I'd say that feature *is not a problem*
for users of that language.

In Python, I maintain that's the case for “end of line as end of
statement”, and for “indentation as block structure”.

-- 
 \   “A computer once beat me at chess, but it was no match for me |
  `\ at kick boxing.” —Emo Philips |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-12 Thread Yingjie Lan
> :The trouble of dealing with long lines can be avoided by a smart

> :editor. It's called line wrap.
> 
> Yeah, usually they just wrap it pretty arbitrarily,
> and you don't have any control, isn't it?

:umm... besides "notepad" pretty much any other serious "programmer editor" 
:program try to do its best to deal with line wrap: the minimal I found is 
:the wrapped line is "indented" at the same level of the flow, but I found 
:editors where you can specify what to do (generally something like "indent 
:the wrapped part 2 levels" or something like that)

Thanks for sharing that, which I am not quite aware of . BTW, do you think
things like eclipse, emacs and vim also has such kind of functionality? 
Best of all, would certainly like to have IDLE have it, as I am teaching 
Python and would like to get them to start with a simple environment.

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


Re: allow line break at operators

2011-08-12 Thread Yingjie Lan





From: Vito 'ZeD' De Tullio 

:umm... besides "notepad" pretty much any other serious "programmer editor" 
:program try to do its best to deal with line wrap: the minimal I found is 
:the wrapped line is "indented" at the same level of the flow, but I found 
:editors where you can specify what to do (generally something like "indent 
:the wrapped part 2 levels" or something like that)

Well, even if one editor can do perfect line wrapping, breaking 
the line at places perfectly pleasing to the eye (put aside the
fact that sometimes the line breaking could be based on the
meaning of the code), it is unlikely to be cross-editor consistent. 

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


Re: String concatenation - which is the fastest way ?

2011-08-12 Thread przemolicc
On Thu, Aug 11, 2011 at 02:48:43PM +0100, Chris Angelico wrote:
> On Thu, Aug 11, 2011 at 2:46 PM,   wrote:
> > This is the way I am going to use.
> > But what is the best data type to hold so many rows and then operate on 
> > them ?
> >
> 
> List of strings. Take it straight from your Oracle interface and work
> with it directly.

Can I use this list in the following way ?
subprocess_1 - run on list between 1 and 1
subprocess_2 - run on list between 10001 and 2
subprocess_3 - run on list between 20001 and 3
etc
...
Sort of indexing ?

Regards
Przemyslaw Bak (przemol)




















































Zmyslowa bielizna? U nas ja znajdziesz!
http://linkint.pl/f29fe
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String concatenation - which is the fastest way ?

2011-08-12 Thread przemolicc
On Thu, Aug 11, 2011 at 02:48:43PM +0100, Chris Angelico wrote:
> On Thu, Aug 11, 2011 at 2:46 PM,   wrote:
> > This is the way I am going to use.
> > But what is the best data type to hold so many rows and then operate on 
> > them ?
> >
> 
> List of strings. [...]

Let's assume I have the whole list in the memory:
Can I use this list in the following way ?
subprocess_1 - run on list between 1 and 1
subprocess_2 - run on list between 10001 and 2
subprocess_3 - run on list between 20001 and 3
etc
...
Can I use sort of indexing on this list ?


Regards
Przemyslaw Bak (przemol)




















































Doladuj telefon przez Internet!
Sprawdz >> http://linkint.pl/f2a06
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String concatenation - which is the fastest way ?

2011-08-12 Thread Chris Angelico
On Thu, Aug 11, 2011 at 3:39 PM,   wrote:
> On Thu, Aug 11, 2011 at 02:48:43PM +0100, Chris Angelico wrote:
>> List of strings. Take it straight from your Oracle interface and work
>> with it directly.
>
> Can I use this list in the following way ?
> subprocess_1 - run on list between 1 and 1
> subprocess_2 - run on list between 10001 and 2
> subprocess_3 - run on list between 20001 and 3
> etc
> ...

Yep! You use list slicing. Working with smaller numbers for an example:

>>> ltrs=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 
>>> 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
>>> ltrs[:10]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
>>> ltrs[10:20]
['k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't']
>>> ltrs[20:]
['u', 'v', 'w', 'x', 'y', 'z']

(I actually created that list as "list(string.ascii_lowercase)" for
what that's worth.)

Slice operations are quite efficient.

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


Re: String concatenation - which is the fastest way ?

2011-08-12 Thread Stefan Behnel

[email protected], 11.08.2011 16:39:

On Thu, Aug 11, 2011 at 02:48:43PM +0100, Chris Angelico wrote:

On Thu, Aug 11, 2011 at 2:46 PM,  wrote:

This is the way I am going to use.
But what is the best data type to hold so many rows and then operate on them ?



List of strings. Take it straight from your Oracle interface and work
with it directly.


Can I use this list in the following way ?
subprocess_1 - run on list between 1 and 1
subprocess_2 - run on list between 10001 and 2
subprocess_3 - run on list between 20001 and 3
etc
...


Sure. Just read the data as it comes in from the database and fill up a 
chunk, then hand that on to a process. You can also distribute it in 
smaller packets, just check what size gives the best throughput.


Still, I'd give each work parcel a number and then reorder the results 
while collecting them, that allows you to vary the chunk size and the 
process size independently, without having to wait for a process that 
happens to take longer.


Stefan

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


Re: allow line break at operators

2011-08-12 Thread Ben Finney
Seebs  writes:

> Question for y'all:
>
> Has anyone here ever ACTUALLY encountered a case where braces -- not
> indentation -- did not match intent in a C-like language?  I'm talking
> only about cases where braces are *actually present*.

What a strange limitation. Why are you not comparing apples with apples?

The correct comparison would be “getting the braces to match the
intended structure” compared with “getting the indentation to match the
intended structure”.

> The Python community, as a whole, seems particularly dogmatic about
> the indentation thing. And coming here as someone who doesn't much
> like it, and has been bitten by it a few times...

As you say, the data is thin on the ground for this issue. Would you
accept the charge that you're being just as dogmatic about the
superiority of braces-as-block-syntax?

If so, good for you; we're all equally dogmatic by your definition.
Let's move on.

If not, what makes your position less dogmatic than ours?

-- 
 \   “We jealously reserve the right to be mistaken in our view of |
  `\  what exists, given that theories often change under pressure |
_o__)  from further investigation.” —Thomas W. Clark, 2009 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


How to Check Write Access of a Folder on Windows

2011-08-12 Thread Ayaskanta Swain
Hi,

 

I have a requirement where I need to check the write permissions on a
directory on Windows platform. I don't want to use the python function
os.access( ), since it does not work correctly on Windows. It is giving
incorrect results to me.

 

Another option of actually creating a temporary file inside the folder &
then deleting it to check whether the user has write permissions or not
is causing performance issues. It is slowing down our application when
we have to check the permissions on hundreds of folders. It also changes
the last access time stamp of the folder.

 

So is there any other way such as using Win32API or Win32 security
modules to check the permissions?

 

Please suggest.

 

Thanks

Ayaskant-

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


RE: How to Check Write Access of a Folder on Windows

2011-08-12 Thread Ayaskanta Swain
Some additional information - I am using python 2.5.1 version & it
cannot be upgraded now to a higher version.

 

Thanks

Ayaskant-



From: Ayaskanta Swain 
Sent: Friday, August 12, 2011 4:11 PM
To: '[email protected]'
Subject: How to Check Write Access of a Folder on Windows

 

Hi,

 

I have a requirement where I need to check the write permissions on a
directory on Windows platform. I don't want to use the python function
os.access( ), since it does not work correctly on Windows. It is giving
incorrect results to me.

 

Another option of actually creating a temporary file inside the folder &
then deleting it to check whether the user has write permissions or not
is causing performance issues. It is slowing down our application when
we have to check the permissions on hundreds of folders. It also changes
the last access time stamp of the folder.

 

So is there any other way such as using Win32API or Win32 security
modules to check the permissions?

 

Please suggest.

 

Thanks

Ayaskant-

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


Re: allow line break at operators

2011-08-12 Thread Steven D'Aprano
Ben Finney wrote:

> Likewise, “end of line as end of statement” has caused me and many
> others problems.

I don't understand this. Can you give an example?

Do you mean, "Sometimes I want more code in a single statement than will
comfortably fit in a single line"?



-- 
Steven

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


Re: How to Check Write Access of a Folder on Windows

2011-08-12 Thread Tim Golden

On 12/08/2011 11:41, Ayaskanta Swain wrote:

Hi,

I have a requirement where I need to check the write permissions on a
directory on Windows platform. I don’t want to use the python function
os.access( ), since it does not work correctly on Windows. It is giving
incorrect results to me.

Another option of actually creating a temporary file inside the folder &
then deleting it to check whether the user has write permissions or not
is causing performance issues. It is slowing down our application when
we have to check the permissions on hundreds of folders. It also changes
the last access time stamp of the folder.

So is there any other way such as using Win32API or Win32 security
modules to check the permissions?


In general, yes. Depends how finnicky you want to get. I take it from
your question that you're pretty much unfamiliar with the Windows
Security APIs and structures? There's a quite a bit of information
around on the subject, but have a look at this first which is at
least Python-oriented:

http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html

The trouble is that do what you want, you need to use the AccessCheck
API (or emulate its functionality) and this isn't currently exposed by
the pywin32 modules. You could run it up yourself with ctypes or by
creating a quick extension for the purpose. Alternatively, as I say,
you could emulate by scanning the ACLs/ACEs and trying to apply some
suitable logic. Frankly, I'd have thought this was harder work :)

Hope that helps

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


Puzzled about the output of my demo of a proof of The Euler Series

2011-08-12 Thread Richard D. Moores
For the first time in my 7 years of using Gmail, I accidentally
deleted my original post and it's one reply by casevh. I found both in
the list archive, and with this post both quote casevh's reply and
answer it. Sorry about my screw up.

On Aug 10, 4:57 pm, "Richard D. Moores"  wrote:
> I saw an interesting proof of the limit of The Euler Series on
> math.stackexchange.com at
> .
> Scroll down to Hans Lundmark's post.
>
> I thought I'd try to see this "pinching down" on the limit of pi**2/6.
> See my attempt, and output for n = 150 at
> . What puzzles me is that
> upper_bound_partial_sum (lines 39 and 60) is always smaller than the
> limit. It should be greater than the limit, right? If not, no pinching
> between upper_bound_partial_sum and lower_bound_partial_sum.
>
> I've checked and double-checked the computation, but can't figure out
> what's wrong.
>
> Thanks,
>
> Dick Moores

The math is correct. The proof only asserts that sum(1/k^2) is between
the upper and lower partial sums. The upper and lower partial sums
both converge to pi^2/6 from below and since the sum(1/k^2) is between
the two partial sums, it must also converge to pi^2/6.

Try calculating sum(1/k^2) for k in range(1, 2**n) and compare that
with the upper and lower sums. I verified it with several values up to
n=20.

casevh

===Dick Moores' reply===

Thank you! I had missed the  2^n -1  on the top of the sigma (see my
image of the inequality expression at
.

So I rewrote the script and now it does what I intended -- show the
pinching down on sum(1/k^2) by the upper sums and the lower sums for
successively larger n. See the new script at
.

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


Re: problem with GTK language

2011-08-12 Thread Laszlo Nagy

On 2011-08-10 16:22, Peter Irbizon wrote:

Hello,
I have strange problem with gtk language in pygtk. When I run .py file 
it shows all gtk labels in my default windows language (slovak). But 
when I compile it with py2exe and run exe file all labels are in 
english. Why this happens? How can I define on program startup which 
language to use? I would like to choose between english and slovak. I 
tryed to set locals in my application but no luck. What am I doing wrong?

Do you have this in your main program?


import  locale
locale.setlocale(locale.LC_ALL,  '')



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


Re: allow line break at operators

2011-08-12 Thread Ben Finney
Steven D'Aprano  writes:

> Ben Finney wrote:
>
> > Likewise, “end of line as end of statement” has caused me and many
> > others problems.
>
> I don't understand this. Can you give an example?

Many times I have split a line expecting that some bracketing syntax
will cause the statement to continue across the split. I've been wrong,
and the code either gave a SyntaxError or, worse, did something
functional but unintended.

That is a problem only because end-of-line (outside some bracketing
syntax) ends a statement.

My point is that I consider that problem to be at least on par in the
severity of the problems caused by indentation-as-block-syntax. That is,
very small compared with the great benefit of the clean and readable
syntax that results.

-- 
 \ “Not to be absolutely certain is, I think, one of the essential |
  `\ things in rationality.” —Bertrand Russell |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-12 Thread Neil Cerutti
On 2011-08-12, Steven D'Aprano
 wrote:
> Chris Angelico wrote:
>
>> Incidentally, I will happily argue the
>> benefits of Python's significant whitespace, even though I disagree
>> with it; there are quite a few. 
>
> Please be careful about conflating significant indentation with significant
> whitespace. Many languages have significant whitespace:
>
> foo bar
>
> is rarely the same thing as
>
> foobar
>
> but is the same as
>
> foo   bar
>
> Python is no different.
>
> The only exception I can think of is *very* early Fortran, and
> that rightly is considered a mistake.

Early versions of Basic were like this, too. It was common to
compress large C64 Basic programs by removing the spaces and
substituting the command synonyms.

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


Re: allow line break at operators

2011-08-12 Thread Thomas Rachel

Am 12.08.2011 03:40 schrieb Steven D'Aprano:


The only exception I can think of is *very* early Fortran, and that rightly
is considered a mistake.


ATARI 800XL. Built-in BASIC, acknowledging every command with "READY". 
Going over it with the cursor results in "ERROR- 6", meaning "no READ 
without DATA"... same as "READ Y".



Thomas, it was a long time ago...
--
http://mail.python.org/mailman/listinfo/python-list


Re: generate and send mail with python: tutorial

2011-08-12 Thread aspineux
On Aug 12, 8:51 am, Dennis Lee Bieber  wrote:
> On Thu, 11 Aug 2011 08:07:09 -0700 (PDT), aspineux 
> declaimed the following in gmane.comp.python.general:
>
> > Hi I have written a tutorial about how to generate and send emails
> > with python.
>
>         Is that really such a difficult task?

Yes it's difficult to make an _universal_ mail parser, able to handle
mails from different MUA, using different charsets.
Some emails that break RFC's requires at least some background
to know which rules can be missed by some MUA !

Handle mail from a unique source or similar sources is easy.
Using try and error method is fine for this kind of job, you don't
even need to care if the email you're parsing match the RFC's or not.

My "parser" functions have been tested over 20.000 mails from all
around the world using some human and automated verifications !

Generating emails is not easy, when mixing internationalized
addresses,
subject and content. Integrating text, html, attachment and embedded
images in one single email looks to me difficult enough to require
some explanations.

At least read carefully all my articles to get an idea about the
difficulty,
this is what I try to explain.

Regards.


>
>         Okay, I didn't really use Python for the entire creation of the
> message... But my first real Python program (using 1.4 or 1.5, whatever
> was included in the first "Programming Python" disk, for AmigaOS) was a
> rudimentary outgoing SMTPd which had to parse headers from  message
> files "queued" by an ARexx script from an Amiga version of ELM, then
> handshake with the ISP SMTPd to relay the message onward. It took less
> than a week after buying the book that I had this ARexx/Python hybrid
> working -- and it worked better than either C-language programs I'd
> downloaded (at that period of time, Amiga email programs ONLY read from
> local spool and queued to local spool; separate programs had to be used
> to read POP3 and send SMTP... My first SMTP utility presumed 1) direct
> connection to destination address, 2) created an email file for each
> address -- problem: if a destination did not have a receiving SMTPd [ie,
> one needed to do an MX lookup instead] it would hang trying to send that
> message, and never process others... The second program used ISP relay
> -- but it only parsed the "TO:" header, and thereby failed to handshake
> CC and BCC destinations)
> --
>         Wulfraed                 Dennis Lee Bieber         AF6VN
>         [email protected]    HTTP://wlfraed.home.netcom.com/

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


Re: generate and send mail with python: tutorial

2011-08-12 Thread Steven D'Aprano
aspineux wrote:

> Hi I have written a tutorial about how to generate and send emails
> with python.
[...]

Thank you, that is an extremely detailed tutorial.

-- 
Steven

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


fork problem

2011-08-12 Thread 守株待兔
in the book ,A call to wait() suspends execution (i.e., waits) until a child 
process (any child process) has completed, terminating either normally or via a 
signal. wait() will then reap the child, releasing any resources. If the child 
has already completed, then wait() just performs the reaping procedure. 
here  is my code 
import os
print "i am parent ",os.getpid()
ret  =  os.fork()
print  "i am here",os.getpid()
if  ret  ==  0:
 os.system('ls')
else:
os.wait()
print "i am runing,who am i? ",os.getpid()

according to the word,the output may be:
i am parent  8014
i am here 8014
i am here 8015
"omitted my file"
i am runing,who am i?  8014
because 8015  is terminated by os.wait().

in fact the output is:

i am parent  8014
i am here 8014
i am here 8015
"omitted my file"
i am runing,who am i?  8015
i am runing,who am i?  8014

i want to know why ??-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fork problem

2011-08-12 Thread aspineux
On Aug 12, 4:18 pm, "守株待兔" <[email protected]> wrote:
> in the book ,A call to wait() suspends execution (i.e., waits) until a child 
> process (any child process) has completed, terminating either normally or via 
> a signal. wait() will then reap the child, releasing any resources. If the 
> child has already completed, then wait() just performs the reaping procedure.
> here  is my code
> import os
> print "i am parent ",os.getpid()
> ret  =  os.fork()
> print  "i am here",os.getpid()
> if  ret  ==  0:
>  os.system('ls')
> else:
> os.wait()
> print "i am runing,who am i? ",os.getpid()
>
> according to the word,the output may be:
> i am parent  8014
> i am here 8014
> i am here 8015
> "omitted my file"
> i am runing,who am i?  8014
> because 8015  is terminated by os.wait().
>
> in fact the output is:
>
> i am parent  8014
> i am here 8014
> i am here 8015
> "omitted my file"
> i am runing,who am i?  8015
> i am runing,who am i?  8014
>
> i want to know why ??

To get what you want, use os.exec() instead of os.system()
or add a os.exit() just after os.system()

Regards

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


Re: Processing a large string

2011-08-12 Thread Peter Otten
Peter Otten wrote:

> goldtech wrote:

>> Say I have a very big string with a pattern like:
>> 
>> akakksssk3dhdhdhdbddb3dkdkdkddk3dmdmdmd3dkdkdkdk3asnsn.
>> 
>> I want to split the sting into separate parts on the "3" and process
>> each part separately. I might run into memory limitations if I use
>> "split" and get a big array(?)  I wondered if there's a way I could
>> read (stream?) the string from start to finish and read what's
>> delimited by the "3" into a variable, process the smaller string
>> variable then append/build a new string with the processed data?

> PS: This has come up before, but I couldn't find the relevant threads...

Alex Martelli a looong time ago:

> from __future__ import generators
> 
> def splitby(fileobj, splitter, bufsize=8192):
> buf = ''
> 
> while True:
> try: 
> item, buf = buf.split(splitter, 1)
> except ValueError:
> more = fileobj.read(bufsize)
> if not more: break
> buf += more
> else:
> yield item + splitter
> 
> if buf:
> yield buf

http://mail.python.org/pipermail/python-list/2002-September/770673.html


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


Re: allow line break at operators

2011-08-12 Thread rantingrick
On Aug 12, 1:34 am, Seebs  wrote:
>
> And part of this really is personal taste.  I *LIKE* having a matching outdent
> for everything.  I like to look at code and see
>         blah
>                 blah
>                         blah
>                 blah
>         blah
>
> because then I know it's balanced.  If one of them is missing, *something is
> wrong*.

What is with you guys and this need to have your hand held to read
code. Out-dents are noise and nothing more. When you're driving on a
two lane highway that becomes one lane, would you forget to merge
(OUTDENT) simply because the "merge sign" was missing? If you did then
i would say you need to keep your eyes on the road (CODE) instead of
looking for signs on the side of the road. In other words; you need to
start acting like an intelligent agent instead of a zombie.

> In other language communities, when I find things about the language
> troublesome, I usually find people offering suggestions for ways to improve
> things, or workarounds, or acknowledging that, yes, that can be annoying.
> But for some reason, in this one, that's apparently against a local taboo.
> So instead of acknowledging that it is conceivably possible for people to
> prefer different things, people say things like "oh, once you've done it a
> bit you'll realize how much better it is and then you'll love it".
> Condescending, smug, and, at least so far, *totally untrue* for me.

Well for indention there is no alternatives. There is either indent/
dendent, or suffer the syntax error.

> I am also weirded out by the claim that a Python which used braces would no
> longer be Python in any way, shape, or form.  If you were to make a C
> derivative which used indentation instead of braces (this should be trivial
> to do with a preprocessor), I can't imagine C programmers claiming it's
> "not C".  Of course it's C; it has the C type system, the C operators, the
> C promotion rules, C linkage and scope and so on... That's C.  It's just a C
> variant which tweaks the punctuation.

Hmm, Python's exclusive use of indent/dedent for denoting blocks is
rather unique in a world of braces (barring a few other less known
languages). Removing that feature and replacing it with braces (or
tags or whatever) would change the language significantly!

Likewise allowing a directive like "use braces = True" would also be
detrimental to our code bases. A language must always strive to remove
ambiguities and multiplicity. Having more than one way to mark blocks
is insanity. You never want to induce more overhead than necessary
because such things are detrimental to work flow and language
evolution.

> If Python with braces wouldn't be Python at all, why on earth does the
> language even exist?  If all you want is indentation-which-matters, it's
> super easy to write a preprocessor for ANY language to do that, and you could
> have every last positive feature, benefit, or valuable trait of Python by
> doing that to any other language.

This statement leads me to believe you have very little experience
with the Python language. Python has many wonderful attributes and
design philosophies. Significant indentation is just ONE of many.

> Unless, of course, there are *other* things that are significant
> about Python.  In which case, a language which preserved all of
> those, but used braces, would still be a kind of Python after all.

I don't understand this need for braces. You yearn so badly to be
dominated by them. Is this a psychological disorder, a Helsinki
syndrome that you cannot shake? There is life after braces my friend,
and the future is bright!

> Long story short:  I think the dismissiveness and hostility I've seen from
> people in the Python community towards people who, for *whatever* reason,
> find the indentation-flow-control thing annoying, is not really helping the
> Python community win converts.  

As much as we love people getting on board we are not about to
sacrifice our strong beliefs in clean source code just so you and
other hardwired C programmers will come along. Indentation is at the
very heart of Pythons philosophy. A philosophy that breaks free from
decades old language design build on the detrimental ideals of multi-
stylism. Good languages do not care about your singularly instinctual
emotion needs for bondage, no, they care about productivity and
readability from a community perspective.

PS: I will admit that a few of our community members can be rather
acerbic at times.

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


Re: allow line break at operators

2011-08-12 Thread rantingrick
On Aug 12, 2:20 am, Chris Angelico  wrote:

> Pike is very [snip]
> Pike's purpose is [snip]
> you go to Pike[snip]
>
> I hope I make myself clear, Josephine?

The only thing that is clear to me is that you have a hidden agenda to
incorporate pike's functionality into Python -- and this is not the
first time!

Chris, this incessant babbling about "pike this" and "pike that" is
starting to get on my nerves. Why don't you go over to comp.lang.pike
and gush to them about how wonderful the language is.

PS: Although i give you brownie point for sucking up to GvR and the
community at large before hinting about "Esox lucius" greatness. Nice!
-- 
http://mail.python.org/mailman/listinfo/python-list


Multiple process output

2011-08-12 Thread Paulo J. Matos

Hi all,

I am have a function which executes a command in the shell. The stdout 
and stderr of the command should be multipled to two strings for stdout 
and stderr respectively and stdout and stderr of the current process 
respectively.


I have done like this:
from subprocess import Popen, PIPE, STDOUT
from select import select
from os import read
from sys import stdout, stderr

def communicate(p):
""" 



Multiplex the subprocess stdout/stderr to the process stdout/stderr 



and a tuple of strings 



"""
output = []
errput = []

while True:
(ready_to_read, _, _) = select([p.stdout, p.stderr], [], [])
dataout = ""
dataerr = ""

if p.stdout in ready_to_read:
dataout = read(p.stdout.fileno(), 1024)
stdout.write(dataout)
output.append(dataout)

if p.stderr in ready_to_read:
dataerr = read(p.stderr.fileno(), 1024)
stderr.write(dataerr)
errput.append(dataerr)

if dataout == "" and dataerr == "":
p.stdout.close()
p.stderr.close()
break

return (''.join(output), ''.join(errput))

def exe(s, cwd=None, output_command=True):
if output_command:
print s
p = Popen(s, stdin=None, stdout=PIPE, stderr=PIPE, shell=True, cwd=cwd)
(output, err) = communicate(p)
rc = p.wait()
return (rc, output, err)


Unfortunately, the program is _sometimes_ but not always getting stuck 
on the call to select. I don't really understand when this happens. Any 
suggestions to the above code so select doesn't block the function?


Cheers,

--
PMatos

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


Problem reading HTTP_COOKIE

2011-08-12 Thread Jack Hatterly

Hi;

I'm trying to get cookies to work and I've traced my problem down to this 
reduced script:



#! /usr/bin/python



import string

import os

import datetime, Cookie, random

import time

import os



def parse_cookie():

  print 'Content-Type: text/html\n'



  print os.environ.get('HTTP_COOKIE')

  print ''

  print ''



if __name__ == "__main__":

  parse_cookie()



It prints "None". However, when I look in my browser's cookie jar, there
 is a cookie "www.my_site.com" where my_site is the site from which I am
 surfing the above script. What gives?

TIA,

Jack

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


Re: What Programing Language are the Largest Website Written In?

2011-08-12 Thread Tim Bradshaw

On 2011-08-02 15:41:06 +0100, ccc31807 said:



Most of these are tech companies. Tech companies are very important,
but so are other kinds of companies. What do manufacturing companies
use, like Ford and Toyota, energy companies like BP and Exxon,
pharmaceutical companies, consumer product companies, and so on? What
about the big retailers, Sears, WalMart, Target, etc.?


A more important metric is how critical the web presence is to the 
company.  For Amazon, say, it's pretty critical, so what they do is 
likely to be interesting: if their site is broken they're not making 
any money.  For Toyota, say, well, an outage would probably be 
embarrassing, but it's not anything like as critical to them.


Unfortunatly I suspect that with web stuff as with other stuff, the 
answer is that it entirely depends.  I am endlessly horrified by the 
poor state of software that is really critical to large companies.


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


Re: String concatenation - which is the fastest way ?

2011-08-12 Thread SigmundV
On Aug 12, 8:10 am, [email protected] wrote:
> Good question but I try to explain what motivates me to do it.
> First reason (I think the most important :-) ) is that I want to learn
> something new - I am new to python (I am unix/storage sysadmin but with 
> programming
> background so python was a natural choice for more complicated
> sysadmin tasks).
> Another reason is that our server (and I am responsible for it) has
> many, many but slow cores (as I had written before). It means that
> parallelization of operations is obvious - the developer is not keen
> to spent much time on it (she is busy) - and for me this is something new
> (among some boring daily tasks ... ;-) ) and fresh :-)
> Another intention is to get some more knowledge about parallelization:
> how to divide some task into subtasks, what is the most optimal way to do it, 
> etc
> And the last reason is that I love performance tuning :-)

When you put it this way I better understand what you're after and why
you do this. And I agree with all your points. Learning something new
is a noble cause in itself. :)

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


Re: What Programing Language are the Largest Website Written In?

2011-08-12 Thread Alec Taylor
C++ (Wt xor CppCMS)

WOOT!

On Sat, Aug 13, 2011 at 1:58 AM, Tim Bradshaw  wrote:
> On 2011-08-02 15:41:06 +0100, ccc31807 said:
>
>>
>> Most of these are tech companies. Tech companies are very important,
>> but so are other kinds of companies. What do manufacturing companies
>> use, like Ford and Toyota, energy companies like BP and Exxon,
>> pharmaceutical companies, consumer product companies, and so on? What
>> about the big retailers, Sears, WalMart, Target, etc.?
>
> A more important metric is how critical the web presence is to the company.
>  For Amazon, say, it's pretty critical, so what they do is likely to be
> interesting: if their site is broken they're not making any money.  For
> Toyota, say, well, an outage would probably be embarrassing, but it's not
> anything like as critical to them.
>
> Unfortunatly I suspect that with web stuff as with other stuff, the answer
> is that it entirely depends.  I am endlessly horrified by the poor state of
> software that is really critical to large companies.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-12 Thread Chris Rebert
On Fri, Aug 12, 2011 at 3:39 AM, Ben Finney  wrote:
> Seebs  writes:
>
>> Question for y'all:
>>
>> Has anyone here ever ACTUALLY encountered a case where braces -- not
>> indentation -- did not match intent in a C-like language?  I'm talking
>> only about cases where braces are *actually present*.
>
> What a strange limitation. Why are you not comparing apples with apples?
>
> The correct comparison would be “getting the braces to match the
> intended structure” compared with “getting the indentation to match the
> intended structure”.

One argument I've heard from braces fans is that sometimes they want
their own structure, which does not match the actual block structure.
Example:

FILE* f = fopen(...);
// do stuff with f
// at this indent level
fclose(f);
// back to normal

But really this is just working around other limitations in the
language (i.e. lack of a with-statement equivalent).

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


Java is killing me! (AKA: Java for Pythonheads?)

2011-08-12 Thread kj



*Please* forgive me for asking a Java question in a Python forum.
My only excuse for this no-no is that a Python forum is more likely
than a Java one to have among its readers those who have had to
deal with the same problems I'm wrestling with.

Due to my job, I have to port some Python code to Java, and write
tests for the ported code.  (Yes, I've considered finding myself
another job, but this is not an option in the immediate future.)

What's giving me the hardest time is that the original Python code
uses a lot of functions with optional arguments (as is natural to
do in Python).  

As far as I can tell (admittedly I'm no Java expert, and have not
programmed in it since 2001), to implement a Java method with n
optional arguments, one needs at least 2**n method definitions.
Even if all but one of these definitions are simple wrappers that
call the one that does all the work, it's still a lot of code to
wade through, for nothing.

That's bad enough, but even worse is writing the unit tests for
the resulting mountain of fluffCode.  I find myself writing test
classes whose constructors also require 2**n definitions, one for
each form of the function to be tested...

I ask myself, how does the journeyman Python programmer cope with
such nonsense?

For the sake of concreteness, consider the following run-of-the-mill
Python function of 3 arguments (the first argument, xs, is expected
to be either a float or a sequence of floats; the second and third
arguments, an int and a float, are optional):

   def quant(xs, nlevels=MAXN, xlim=MAXX):
if not hasattr(xs, '__iter__'):
return spam((xs,), n, xlim)[0]

if _bad_quant_args(xs, nlevels, xlim):
raise TypeError("invalid arguments")

retval = []
for x in xs:
# ...
# elaborate acrobatics that set y
# ...
retval.append(y)

return retval

My Java implementation of it already requires at least 8 method
definitions, with signatures:

short[] quant (float[], int, float) 
  
short[] quant (float[], int   ) 
  
short[] quant (float[],  float) 
  
short[] quant (float[]) 
  

  
short   quant (float  , int, float) 
  
short   quant (float  , int   ) 
  
short   quant (float  ,  float) 
  
short   quant (float  ) 
  

Actually, for additional reasons, too arcane to go into, I also
need four more:

short   quant (Float  , Integer, Float) 
  
short   quant (Float  , Integer   ) 
  
short   quant (Float  ,  Float) 
  
short   quant (Float  ) 
  

Writing JUnit tests for these methods is literally driving me
INSANE.

Some advice on implementing and testing functions with optional
arguments in Java would be appreciated.

TIA!

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


Re: allow line break at operators

2011-08-12 Thread Seebs
On 2011-08-12, Ben Finney  wrote:
> Seebs  writes:
>> I am pretty sure Python is a pretty nice language. However, the
>> indentation thing has screwed me a few times. Furthermore, I know
>> people who like Python a great deal and acknowledge, without much
>> difficulty, that the indentation thing has caused problems or
>> incompatibilities for them.

> Yes. It's caused problems for me too, so I'm not going to deny that.

> This is different from saying ???indentation as block structure??? is a
> problem; that statement is what I disagree with, and what I think most
> respondents who disagree with you are objecting to.

See below; I think I agree with what I meant by it, and disagree with what
you seem to interpret it as.  Your interpretation makes as much sense as mine,
so far as I can tell.

> I don't see anyone making the denials you're referring to there. If I
> did, you would have my support in considering those denials mistaken.

I suspect, thinking about it more, that it's a communications problem.

> Likewise, ???end of line as end of statement??? has caused me and many
> others problems. I'd go so far as to say that any Python programmer for
> whom that's not true has not done any significant Python programming.
> That doesn't make ???end of line as end of statement??? a problem.

True, although it does make it a thing which *has* at least one problem.

> If a language feature is beneficial in far greater proportion to the
> inconveniences of that feature, I'd say that feature *is not a problem*
> for users of that language.

I wouldn't.

Lemme give a concrete example, from C, since that's the language I know best.
There are sound technical reasons for which C lets you manipulate pointers.
If you couldn't, it wouldn't be C, and you couldn't do the bulk of the stuff
that makes C useful.  But...

Pointer manipulation leads to crashes.  LOTS of crashes.  I have never met
a C programmer with over a day or two of experience who has not had a
program crash due to some mishap involving a pointer.

When people say that a language like, say, Java, is trying to solve the
problems of C's pointer system, I think that's a reasonable thing to try to
do.  There are tradeoffs.  But it would be, IMHO, silly to claim that there
are no problems with pointers; there are just benefits which outweigh them
*for the things the language is trying to do*.

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


Re: allow line break at operators

2011-08-12 Thread Seebs
On 2011-08-12, Ben Finney  wrote:
> Seebs  writes:
>> Question for y'all:
>>
>> Has anyone here ever ACTUALLY encountered a case where braces -- not
>> indentation -- did not match intent in a C-like language?  I'm talking
>> only about cases where braces are *actually present*.

> What a strange limitation. Why are you not comparing apples with apples?

I am trying to.  I'm trying to compare C-like languages, with braces, to
Python, with indentation.

> The correct comparison would be ???getting the braces to match the
> intended structure??? compared with ???getting the indentation to match the
> intended structure???.

Right.

I have seen Python programs in which indentation, while it obviously matched
what actually happened, did not match intent.  It is (at least in principle)
easier to debug because you can see that, but...

I've seen people in C do stuff like:

for (i = 0; i < N; ++i);
a[i] = 0;

This is clearly a case where indentation matches intent, but doesn't match
functionality, because C allows indentation to not-match functionality; this
is the famous problem Python is solving.

However, I've never, ever, seen a problem like that *when people were using
braces*.

An apples-to-apples comparison between indentation and braces should be a
comparison *to braces*, not to people who "cleverly" omit braces.

(If you are looking for a debate on whether C's optional-braces are a good
idea, I'm afraid you will have to look elsewhere; if it were up to me, I
would totally approve a language change making them mandatory.)

> As you say, the data is thin on the ground for this issue. Would you
> accept the charge that you're being just as dogmatic about the
> superiority of braces-as-block-syntax?

I don't think so.

> If not, what makes your position less dogmatic than ours?

A couple of things.

1.  I do assert that people who are happy with an editor and have been using
it for twenty years ought to change their editor to accommodate a language
which uses braces.
2.  I will happily grant that braces, written legibly, cost you an extra
line per block, and that this space cost can make it harder to see all the
code at once.
3.  I don't have a problem agreeing that there certainly appear to be people
for whom the Python syntax is easier to read.

I think #1 is the real point at which I think there's a dogmatism problem.
Maybe editors shouldn't "helpfully" convert spaces to tabs, but that feature
has been nearly entirely beneficial to me in everything else I've edited
for a long time, and I don't *want* to learn a new editor just for one
language.

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


Re: allow line break at operators

2011-08-12 Thread Seebs
On 2011-08-12, Chris Angelico  wrote:
> On Fri, Aug 12, 2011 at 7:34 AM, Seebs  wrote:
>> If Python with braces wouldn't be Python at all, why on earth does the
>> language even exist?

> Every language has its philosophy.

Yes.

> Etcetera. These are the philosophical decisions made by GvR and the
> Python community, and these define Python's syntax. If you go against
> these, you could make something that compiles down to Python's byte
> code; in fact, I'd say you could make something that produces a .pyc
> file and then hands it to the regular Python interpreter for
> execution. Is it Python? No, no more than NetREXX is Java just because
> it can make a .class file. It's a different language.

I would argue that any pure syntactic-sugar change which can be done entirely
by a naive preprocessor does not constitute a significant shift in the
language itself.

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


Re: allow line break at operators

2011-08-12 Thread Seebs
On 2011-08-12, rantingrick  wrote:
> What is with you guys and this need to have your hand held to read
> code.

Good question!  Great to see that the helpful and welcoming community
is living up to its reputation.

My brain has quirks.  Some people call them defects, some don't, but it
really doesn't matter; there are things about which my brain is just plain
unreliable and I rely moderately heavily on extra visual cues to reduce
the frequency with which I get things wrong when skimming.

> Out-dents are noise and nothing more.

Not for me.

> When you're driving on a
> two lane highway that becomes one lane, would you forget to merge
> (OUTDENT) simply because the "merge sign" was missing?

No, because the *LANE BOUNDARIES* would move.

> If you did then
> i would say you need to keep your eyes on the road (CODE) instead of
> looking for signs on the side of the road. In other words; you need to
> start acting like an intelligent agent instead of a zombie.

Interesting theory.

I propose we extend it to expression processing in general.  Instead
of writing
a = (x + y) * z
let's just write
a = (x + y * z
It's obvious that no one would have needed to introduce parentheses here
unless they wanted to bind the + more closely than the *, so the ) is
just noise and not needed.

> Hmm, Python's exclusive use of indent/dedent for denoting blocks is
> rather unique in a world of braces (barring a few other less known
> languages). Removing that feature and replacing it with braces (or
> tags or whatever) would change the language significantly!

It would, but unless that's the only distinctive trait of the language,
I don't think it would make the language cease to be Python.

> Likewise allowing a directive like "use braces = True" would also be
> detrimental to our code bases. A language must always strive to remove
> ambiguities and multiplicity. Having more than one way to mark blocks
> is insanity. You never want to induce more overhead than necessary
> because such things are detrimental to work flow and language
> evolution.

Agreed.

> This statement leads me to believe you have very little experience
> with the Python language. Python has many wonderful attributes and
> design philosophies. Significant indentation is just ONE of many.

It was a reductio-ad-absurdum.

> I don't understand this need for braces. You yearn so badly to be
> dominated by them. Is this a psychological disorder, a Helsinki
> syndrome that you cannot shake? There is life after braces my friend,
> and the future is bright!

Man, you really love pushing them buttons, don't you?

You don't understand a thing.  Therefore... there is no such thing, anyone
who experiences life differently from you needs to be insulted?

> As much as we love people getting on board we are not about to
> sacrifice our strong beliefs in clean source code just so you and
> other hardwired C programmers will come along.

But you will happily insult people and call them names in order to
keep them from having anything to listen to?

> PS: I will admit that a few of our community members can be rather
> acerbic at times.

Yeah.  And the thing is...  This can't possibly lead to convincing people of
your position, so presumably the purpose is that you don't want anyone who
didn't start out agreeing with you to ever come to agree with you?  Why's
that?

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


Re: Java is killing me! (AKA: Java for Pythonheads?)

2011-08-12 Thread Nathan Rice


public FooClass(String requiredArgument1, Long requiredArgument2, map
yourOptionalArgumentMap) {
   ...
}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Java is killing me! (AKA: Java for Pythonheads?)

2011-08-12 Thread MRAB

On 12/08/2011 18:02, kj wrote:




*Please* forgive me for asking a Java question in a Python forum.
My only excuse for this no-no is that a Python forum is more likely
than a Java one to have among its readers those who have had to
deal with the same problems I'm wrestling with.

Due to my job, I have to port some Python code to Java, and write
tests for the ported code.  (Yes, I've considered finding myself
another job, but this is not an option in the immediate future.)

What's giving me the hardest time is that the original Python code
uses a lot of functions with optional arguments (as is natural to
do in Python).

As far as I can tell (admittedly I'm no Java expert, and have not
programmed in it since 2001), to implement a Java method with n
optional arguments, one needs at least 2**n method definitions.
Even if all but one of these definitions are simple wrappers that
call the one that does all the work, it's still a lot of code to
wade through, for nothing.

That's bad enough, but even worse is writing the unit tests for
the resulting mountain of fluffCode.  I find myself writing test
classes whose constructors also require 2**n definitions, one for
each form of the function to be tested...

I ask myself, how does the journeyman Python programmer cope with
such nonsense?

For the sake of concreteness, consider the following run-of-the-mill
Python function of 3 arguments (the first argument, xs, is expected
to be either a float or a sequence of floats; the second and third
arguments, an int and a float, are optional):

def quant(xs, nlevels=MAXN, xlim=MAXX):
 if not hasattr(xs, '__iter__'):
 return spam((xs,), n, xlim)[0]

 if _bad_quant_args(xs, nlevels, xlim):
 raise TypeError("invalid arguments")

 retval = []
 for x in xs:
 # ...
 # elaborate acrobatics that set y
 # ...
 retval.append(y)

 return retval

My Java implementation of it already requires at least 8 method
definitions, with signatures:


[snip]

I would declare:

 short[] quant (float[], int, float)
 short   quant (Float  , Integer, Float)

and see how it goes.

"float" and "int" should be boxed to "Float" and "Integer"
automatically.

If the second and third arguments are frequently the default, then I
would also declare:

 short[] quant (float[])
 short   quant (Float  )
--
http://mail.python.org/mailman/listinfo/python-list


Re: Java is killing me! (AKA: Java for Pythonheads?)

2011-08-12 Thread Billy Earney
Look into jython.  You might be able to run your python code, directly in
java. :)

http://www.jython.org/


On Fri, Aug 12, 2011 at 12:02 PM, kj  wrote:

>
>
>
> *Please* forgive me for asking a Java question in a Python forum.
> My only excuse for this no-no is that a Python forum is more likely
> than a Java one to have among its readers those who have had to
> deal with the same problems I'm wrestling with.
>
> Due to my job, I have to port some Python code to Java, and write
> tests for the ported code.  (Yes, I've considered finding myself
> another job, but this is not an option in the immediate future.)
>
> What's giving me the hardest time is that the original Python code
> uses a lot of functions with optional arguments (as is natural to
> do in Python).
>
> As far as I can tell (admittedly I'm no Java expert, and have not
> programmed in it since 2001), to implement a Java method with n
> optional arguments, one needs at least 2**n method definitions.
> Even if all but one of these definitions are simple wrappers that
> call the one that does all the work, it's still a lot of code to
> wade through, for nothing.
>
> That's bad enough, but even worse is writing the unit tests for
> the resulting mountain of fluffCode.  I find myself writing test
> classes whose constructors also require 2**n definitions, one for
> each form of the function to be tested...
>
> I ask myself, how does the journeyman Python programmer cope with
> such nonsense?
>
> For the sake of concreteness, consider the following run-of-the-mill
> Python function of 3 arguments (the first argument, xs, is expected
> to be either a float or a sequence of floats; the second and third
> arguments, an int and a float, are optional):
>
>   def quant(xs, nlevels=MAXN, xlim=MAXX):
>if not hasattr(xs, '__iter__'):
>return spam((xs,), n, xlim)[0]
>
>if _bad_quant_args(xs, nlevels, xlim):
>raise TypeError("invalid arguments")
>
>retval = []
>for x in xs:
># ...
># elaborate acrobatics that set y
># ...
>retval.append(y)
>
>return retval
>
> My Java implementation of it already requires at least 8 method
> definitions, with signatures:
>
>short[] quant (float[], int, float)
>short[] quant (float[], int   )
>short[] quant (float[],  float)
>short[] quant (float[])
>
>short   quant (float  , int, float)
>short   quant (float  , int   )
>short   quant (float  ,  float)
>short   quant (float  )
>
> Actually, for additional reasons, too arcane to go into, I also
> need four more:
>
>short   quant (Float  , Integer, Float)
>short   quant (Float  , Integer   )
>short   quant (Float  ,  Float)
>short   quant (Float  )
>
> Writing JUnit tests for these methods is literally driving me
> INSANE.
>
> Some advice on implementing and testing functions with optional
> arguments in Java would be appreciated.
>
> TIA!
>
> kj
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Java is killing me! (AKA: Java for Pythonheads?)

2011-08-12 Thread Alain Ketterlin
kj  writes:

[...]
>def quant(xs, nlevels=MAXN, xlim=MAXX):
[...]
> My Java implementation of it already requires at least 8 method
> definitions, with signatures:

(BTW, your approach won't work if several optionals have the same type.)
[...]

- use Integer, Float, etc. everywhere. The compiler will box primitive
  types as needed at call sites
- re. default values (on positional params), use null to indicate a use
  of the default, or use ellipsis, or use class-provided static fields
  at call sites, or use a special class to represent all the optional
  parameters
- re. named parameters with default, use a map, or change the call sites
  to remove them

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


Re: allow line break at operators

2011-08-12 Thread rantingrick
On Aug 12, 11:33 am, Seebs  wrote:
>
> My brain has quirks.  Some people call them defects, some don't, but it
> really doesn't matter; there are things about which my brain is just plain
> unreliable and I rely moderately heavily on extra visual cues to reduce
> the frequency with which I get things wrong when skimming.

I think that really boils down to you refusing to open your eyes up to
new ways of doing things. You are clutching the past and it is taking
you down with it. Pry your lips from Ritchie's left teet and stop
slurping that "brace" milk; because it is polluting your mind!

> > When you're driving on a
> > two lane highway that becomes one lane, would you forget to merge
> > (OUTDENT) simply because the "merge sign" was missing?
>
> No, because the *LANE BOUNDARIES* would move.

The "lane boundaries" will also move whilst reading code that uses the
indent/dedent paradigm. Are you honestly telling me that you will skip
over a four spaced dedent without seeing it however you can easily
spot a single closing brace and instantly "know" which corresponding
opener brace to which it referrers without looking, and counting, and
wasting time? Sorry, i just don't believe you.

> I propose we extend it to expression processing in general.  Instead
> of writing
>         a = (x + y) * z
> let's just write
>         a = (x + y * z

I'm glad you brought this up! How about this instead:

a = x + y * z

...where the calculation is NOT subject to operator precedence? I
always hated using parenthesis in mathematical calculations. All math
should resolve in a linear fashion. 3+3*2 should always be 12 and NOT
9!

> It's obvious that no one would have needed to introduce parentheses here
> unless they wanted to bind the + more closely than the *, so the ) is
> just noise and not needed.

I would even go as far to use a special set of brackets for linear
calculations before using only one, or playing the precedence game.

> > As much as we love people getting on board we are not about to
> > sacrifice our strong beliefs in clean source code just so you and
> > other hardwired C programmers will come along.
>
> But you will happily insult people and call them names in order to
> keep them from having anything to listen to?

I am not trying to discredit you simply by disagreeing with you. I
have offered facts as to why significant indention is far superior to
braces and yet you continue to use the same emotionally charged babble
in your defense. When you offer some real facts then i will give then
just consideration, until then i will "try" to enlighten you of the
merits of significant indentation.

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


Re: Java is killing me! (AKA: Java for Pythonheads?)

2011-08-12 Thread Jeffrey Gaynor
One Java-eque  solution is to pass in an object that has the arguments and 
build the validity logic into that object.

So you have

public class LimitsAndLevels{
 float[] whatever = null;
 float anotherOne = 0.0; // or maybe some other overloaded value

  public float[] getWhatever(){
 isValid();
return whatever; 
  }
  public boolean hasWhatever(){
 isValid();
 return whatever != null;
  }

  public void isValid(){
   // Code to check validity
   // Probably throws an IllegalArgumentException if you need.
   // That exception extends RuntimeException, so no need to put in a 
throws list
  }
}



Then you pass this, e.g., 

public class HeavyLifter{
  public int[] quant(LimitsAndLevels args){
// acrobatics.

  }
}

Hope this helps...

Jeff


- Original Message -
From: "kj" 
To: [email protected]
Sent: Friday, August 12, 2011 12:02:38 PM
Subject: Java is killing me! (AKA: Java for Pythonheads?)




*Please* forgive me for asking a Java question in a Python forum.
My only excuse for this no-no is that a Python forum is more likely
than a Java one to have among its readers those who have had to
deal with the same problems I'm wrestling with.

Due to my job, I have to port some Python code to Java, and write
tests for the ported code.  (Yes, I've considered finding myself
another job, but this is not an option in the immediate future.)

What's giving me the hardest time is that the original Python code
uses a lot of functions with optional arguments (as is natural to
do in Python).  

As far as I can tell (admittedly I'm no Java expert, and have not
programmed in it since 2001), to implement a Java method with n
optional arguments, one needs at least 2**n method definitions.
Even if all but one of these definitions are simple wrappers that
call the one that does all the work, it's still a lot of code to
wade through, for nothing.

That's bad enough, but even worse is writing the unit tests for
the resulting mountain of fluffCode.  I find myself writing test
classes whose constructors also require 2**n definitions, one for
each form of the function to be tested...

I ask myself, how does the journeyman Python programmer cope with
such nonsense?

For the sake of concreteness, consider the following run-of-the-mill
Python function of 3 arguments (the first argument, xs, is expected
to be either a float or a sequence of floats; the second and third
arguments, an int and a float, are optional):

   def quant(xs, nlevels=MAXN, xlim=MAXX):
if not hasattr(xs, '__iter__'):
return spam((xs,), n, xlim)[0]

if _bad_quant_args(xs, nlevels, xlim):
raise TypeError("invalid arguments")

retval = []
for x in xs:
# ...
# elaborate acrobatics that set y
# ...
retval.append(y)

return retval

My Java implementation of it already requires at least 8 method
definitions, with signatures:

short[] quant (float[], int, float) 
  
short[] quant (float[], int   ) 
  
short[] quant (float[],  float) 
  
short[] quant (float[]) 
  

  
short   quant (float  , int, float) 
  
short   quant (float  , int   ) 
  
short   quant (float  ,  float) 
  
short   quant (float  ) 
  

Actually, for additional reasons, too arcane to go into, I also
need four more:

short   quant (Float  , Integer, Float) 
  
short   quant (Float  , Integer   ) 
  
short   quant (Float  ,  Float) 
  
short   quant (Float  ) 
  

Writing JUnit tests for these methods is literally driving me
INSANE.

Some advice on implementing and testing functions with optional
arguments in Java would be appreciated.

TIA!

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

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

Re: Java is killing me! (AKA: Java for Pythonheads?)

2011-08-12 Thread Miki Tebeka
You can probably do that with varargs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: generate and send mail with python: tutorial

2011-08-12 Thread aspineux
On Aug 12, 3:38 pm, Steven D'Aprano  wrote:
> aspineux wrote:
> > Hi I have written a tutorial about how to generate and send emails
> > with python.
>
> [...]
>
> Thank you, that is an extremely detailed tutorial.

Thanks,  It was my intention

Alain

>
> --
> Steven

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


Re: allow line break at operators

2011-08-12 Thread Seebs
On 2011-08-12, Chris Rebert  wrote:
> One argument I've heard from braces fans is that sometimes they want
> their own structure, which does not match the actual block structure.

EWW!

> Example:
>
> FILE* f = fopen(...);
> // do stuff with f
> // at this indent level
> fclose(f);
> // back to normal
>
> But really this is just working around other limitations in the
> language (i.e. lack of a with-statement equivalent).

That's horrid.

FWIW, the C idiom is:

{
FILE *f = ...
...
fclose(f);
}

It isn't used all that widely, but it is a lot less horrible than
random indenting would be.

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


Re: allow line break at operators

2011-08-12 Thread Chris Angelico
On Fri, Aug 12, 2011 at 4:33 PM, rantingrick  wrote:
> On Aug 12, 2:20 am, Chris Angelico  wrote:
>
>> Pike is very [snip]
>> Pike's purpose is [snip]
>> you go to Pike[snip]
>>
>> I hope I make myself clear, Josephine?
>
> The only thing that is clear to me is that you have a hidden agenda to
> incorporate pike's functionality into Python -- and this is not the
> first time!
>
> Chris, this incessant babbling about "pike this" and "pike that" is
> starting to get on my nerves. Why don't you go over to comp.lang.pike
> and gush to them about how wonderful the language is.

Yeah, it's something I've mentioned a few times. I think people have
mentioned C on this list a few times, too; also lisp. Of course, since
this is the Python mailing list (or newsgroup, depending where you
read it), we aren't allowed to mention any other languages at all. Mea
culpa.

I'm not seeking to add Pike's functionality into Python. I want the
two languages to be different, and I want the world to have different
languages. Diversity and choice promote quality in ways that you don't
seem to understand.

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


Re: __all__

2011-08-12 Thread Ethan Furman

Paul Woolcock wrote:
The gurus will have to correct me if this is not an accepted practice, 
but I know some projects (Fabric is the one that comes to mind) will 
define a submodule specifically for the 'from blah import *' situation. 
The submodule would be called "api", or something like that, so you can 
do: 'from mymodule.api import *' to separate the items you want to 
include in your public api, while still keeping other names importable 
by 'import blah'


Have I said lately how much I *love* Python?  Programming is fun again!

Thanks, Paul, that was the clue I needed.  Had to do some thinking since 
dbf is back to a single module, and no longer a package... here's what I 
came up with:


-
class fake_module(object):
def __init__(self, name, *args):
self.name = name
self.__all__ = []
for func in args:
name = func.__name__
self.__dict__[name] = func
self.__all__.append(name)
def register(self):
sys.modules["%s.%s" % (__name__, self.name)] = self
-

then in my module (towards the bottom since I have to have all my 
functions/classes written that I want to include) I can have


fake_module('api', class1, class2, func1, exception1).register()

Now somebody else who wants to include the classes, exceptions, etc, 
that make up the primary part of the dbf module can do


from dbf.api import *

but

help(dbf)

will continue to list all the other public utility stuff (defined in 
dbf.__all__) normally.


Thanks to all!

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


Re: allow line break at operators

2011-08-12 Thread Chris Angelico
On Fri, Aug 12, 2011 at 5:33 PM, Seebs  wrote:
> I've seen people in C do stuff like:
>
>        for (i = 0; i < N; ++i);
>                a[i] = 0;
>
> This is clearly a case where indentation matches intent, but doesn't match
> functionality, because C allows indentation to not-match functionality; this
> is the famous problem Python is solving.
>

There's several solutions to this. One is linting utilities that
detect unexpectedly-indented code, which is the concept that Python
took to the logical extent of syntactic errors. Another is (again
linting) to disallow a direct trailing semicolon; if you want an empty
body, you put whitespace before the semicolon.

But that wasn't your point, I realise :)

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


Re: allow line break at operators

2011-08-12 Thread Chris Angelico
On Fri, Aug 12, 2011 at 6:57 PM, rantingrick  wrote:
> I'm glad you brought this up! How about this instead:
>
>    a = x + y * z
>
> ...where the calculation is NOT subject to operator precedence? I
> always hated using parenthesis in mathematical calculations. All math
> should resolve in a linear fashion. 3+3*2 should always be 12 and NOT
> 9!

Why is left-to-right inherently more logical than
multiplication-before-addition? Why is it more logical than
right-to-left? And why is changing people's expectations more logical
than fulfilling them? Python uses the + and - symbols to mean addition
and subtraction for good reason. Let's not alienate the mathematical
mind by violating this rule. It would be far safer to go the other way
and demand parentheses on everything.

Incidentally, in the original expression, it would be slightly more
sane to write it as:

a = x + y) * z

borrowing from the musical concept that a repeat sign with no
corresponding begin-repeat means to repeat from the beginning. But
both of these violate XKCD 859.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-12 Thread Ethan Furman

Chris Angelico wrote:

Incidentally, in the original expression, it would be slightly more
sane to write it as:

a = x + y) * z

borrowing from the musical concept that a repeat sign with no
corresponding begin-repeat means to repeat from the beginning. But
both of these violate XKCD 859.


Argh!  ;)

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


Re: allow line break at operators

2011-08-12 Thread Chris Kaynor
On Fri, Aug 12, 2011 at 1:09 PM, Chris Angelico  wrote:

> On Fri, Aug 12, 2011 at 6:57 PM, rantingrick 
> wrote:
> > I'm glad you brought this up! How about this instead:
> >
> >a = x + y * z
> >
> > ...where the calculation is NOT subject to operator precedence? I
> > always hated using parenthesis in mathematical calculations. All math
> > should resolve in a linear fashion. 3+3*2 should always be 12 and NOT
> > 9!
>
> Why is left-to-right inherently more logical than
> multiplication-before-addition? Why is it more logical than
> right-to-left? And why is changing people's expectations more logical
> than fulfilling them? Python uses the + and - symbols to mean addition
> and subtraction for good reason. Let's not alienate the mathematical
> mind by violating this rule. It would be far safer to go the other way
> and demand parentheses on everything.
>

Left-to-right is more logical because that is the choice made by the English
language (which I will note, we are using right now). Also, ignoring
operator precedence, left-to-right is the way math equations evaluate. See 4
/ 2 * 3 - you get 6, not (2/3) and not (3/2).

Now, I would not suggest changing the multiplication before addition rule,
for the very reason you mention: in many cases, the established rule is
expected, but that does not mean it is more logical.

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


Re: Problem reading HTTP_COOKIE

2011-08-12 Thread Chris Angelico
On Fri, Aug 12, 2011 at 4:55 PM, Jack Hatterly  wrote:
> It prints "None". However, when I look in my browser's cookie jar, there is
> a cookie "www.my_site.com" where my_site is the site from which I am surfing
> the above script. What gives?
>

I assume that what you mean is that it prints "None" even after you
hit F5 to reload the page, as the first run of the script will never
have a cookie.

Your script is now not actually setting any cookie. What cookie are
you seeing in your browser? It may be something created and consumed
by your framework, somewhere.

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


Re: Java is killing me! (AKA: Java for Pythonheads?)

2011-08-12 Thread Chris Angelico
On Fri, Aug 12, 2011 at 6:02 PM, kj  wrote:
> I ask myself, how does the journeyman Python programmer cope with
> such nonsense?
>

Firstly, figure out how many combinations of optional arguments
actually make sense. Any that don't, don't support. That may well cut
it down significantly. And then, if there are any that make sense but
will be really rare (eg if you allow optional specification of a max
and a min, and most times you'll use either both bounds or neither),
you can save a few by having the "optional" argument specified with a
sentinel meaning "default". It's ugly in a few places to justify
simplicity in most.

If you really need 100% flexibility, then the suggestions already
posted will definitely be the best.

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


Re: Searching for Lottery drawing list of ticket match...

2011-08-12 Thread MrPink
Boy, that was a lot more elegant that I would have thought.
Though hard for a greenhorn like me to really understand how the
assignment are working, etc.

Anyway, what are these kind of statement call so that I can read up
more on this?
What Python feature are you using?

  num_whites = ticket_whites & drawing_whites
  black_matching = ticket_black == drawing_black

Thanks,


On Aug 10, 11:35 pm, Miki Tebeka  wrote:
> Python built in types are enough for this problem IMO. You can use sets of 
> tuples to specify ticket and drawings and then just do set intersection.
>
> Say the drawing is set([(5, 'wb'), (1, 'wb'), (45, 'wb'), (23, 'wb'), (27, 
> 'wb')]) (keeping black ball out). The you can create a score function:
>
> Side note: I might used a namedtuple to have drawing.whites, drawing.black.
>
> def score(ticket_whites, ticket_black, drawing_whites, drawing_black):
>     num_whites = ticket_whites & drawing_whites
>     black_matching = ticket_black == drawing_black
>     return {
>         (2, True)  : 1,
>         (3, False) : 2,
>         (3, True)  : 3,
>         (4, False) : 4,
>         (4, True)  : 5,
>         (5, False) : 6,
>         (5, True)  : 10
>     }[(num_whites, black_matching)]

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


Re: Searching for Lottery drawing list of ticket match...

2011-08-12 Thread Chris Kaynor
On Fri, Aug 12, 2011 at 1:47 PM, MrPink  wrote:

> Boy, that was a lot more elegant that I would have thought.
> Though hard for a greenhorn like me to really understand how the
> assignment are working, etc.
>
> Anyway, what are these kind of statement call so that I can read up
> more on this?
> What Python feature are you using?
>
>  num_whites = ticket_whites & drawing_whites
>

This is a set intersection, using the "bit-wise and" operator (&). It can
also be written as either of:
num_whites = (ticket_whites & drawing_whites) # Makes it a bit clearer
that the "bit-wise and" operator runs before the "assignment" (=) operator.
num_whites = ticket_whites.intersection(drawing_whites) # Calls the
actual method rather than using the operator. A bit more verbose.


>  black_matching = ticket_black == drawing_black
>

This is just the result of an equality operator being assigned. It may be a
bit clearer if you see it as:
black_matching = (ticket_black == drawing_black)


>
> Thanks,
>
>
For more details, you can look up sets (both the math kind and the specific
Python implementation are relevant):
http://docs.python.org/library/stdtypes.html#set
http://en.wikipedia.org/wiki/Set_(mathematics)
http://en.wikipedia.org/wiki/Set_theory

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


Re: allow line break at operators

2011-08-12 Thread Seebs
On 2011-08-12, Chris Angelico  wrote:
> Why is left-to-right inherently more logical than
> multiplication-before-addition?

I'd say it's certainly "more Pythonic in a vacuum".
Multiplication-before-addition, and all the related rules, require
you to know a lot of special rules which are not visible in the
code, and many of which have no real logical basis.  Left-to-right
is, if nothing else, the way the majority of us read.

The problem is that since everyone's used precedence before, not using
it violates the principle of least astonishment.

... Hmm.  There is a thought; I think it may be useful to distinguish
between "Pythonic" and "Pythonic in a vacuum".  That is to say, there
are things which would fit the basic philosophy of Python very well
if previous programming languages and tools were not widespread, and
there are other things which fit anyway.  Using a simple left-to-right
evaluation would probably be easier for people to understand, and
more self-explanatory, *IF* there were no prior art.

> Why is it more logical than
> right-to-left? And why is changing people's expectations more logical
> than fulfilling them?

Well, playing devil's advocate's advocate here... You could argue that
switching from braces to indentation might be "changing" peoples'
expectations, or might be fulfilling them, depending on the people.

I think there's certainly cases where it is probably better to say
"that expectation proves to make it impossible to build a clean
language, so we're going to ask you to do things this way", and cases
where it is probably better to say "that expectation is very deeply
established, and doesn't really hurt the language, so we'll adapt
to you".

> Python uses the + and - symbols to mean addition
> and subtraction for good reason. Let's not alienate the mathematical
> mind by violating this rule. It would be far safer to go the other way
> and demand parentheses on everything.

I wouldn't mind that.

> Incidentally, in the original expression, it would be slightly more
> sane to write it as:
>
> a = x + y) * z
>
> borrowing from the musical concept that a repeat sign with no
> corresponding begin-repeat means to repeat from the beginning. But
> both of these violate XKCD 859.

Yes, yes they do.

Huh.

You know, that's why the outdents-without-symbols bug me; I have a
thing with a colon on it introducing something, and then there's nothing
ending it.  I want that match so I can let the naive stack-depth-counter
off somewhere in my brain do its thing without leaving me with a huge
feeling of unclosed blocks.

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


Re: allow line break at operators

2011-08-12 Thread Seebs
On 2011-08-12, rantingrick  wrote:
> On Aug 12, 11:33?am, Seebs  wrote:
>> My brain has quirks. ?Some people call them defects, some don't, but it
>> really doesn't matter; there are things about which my brain is just plain
>> unreliable and I rely moderately heavily on extra visual cues to reduce
>> the frequency with which I get things wrong when skimming.

> I think that really boils down to you refusing to open your eyes up to
> new ways of doing things.

You think that, then?  Okay.

> You are clutching the past and it is taking
> you down with it.

I see.  This is a brilliant new theory.  I will further explore the notion
that actually my brain is 100% normal with no limitations except that I have
used languages with braces.  Doubtless this will prove illuminating.

>> No, because the *LANE BOUNDARIES* would move.

> The "lane boundaries" will also move whilst reading code that uses the
> indent/dedent paradigm. Are you honestly telling me that you will skip
> over a four spaced dedent without seeing it however you can easily
> spot a single closing brace and instantly "know" which corresponding
> opener brace to which it referrers without looking, and counting, and
> wasting time? Sorry, i just don't believe you.

Nope, not telling you that.  Here's my example:

if foo:
blah
blah
blah
if bar:
moreblah
moreblah
if quux:
typingisboring
typingisboring
typingisboring
moreblah
moreblah
if baz:
somuchblah
somuchblah
somuchblah
somuchblah
somuchblah
somuchblah
somuchblah
somuchblah
abitmoreblah

It's not easy for me to be sure, looking at something roughly like that,
what's being closed and what isn't.  If I have braces, I can tell how many
things are being closed.  I like that.  It makes me happy.

>> I propose we extend it to expression processing in general. ?Instead
>> of writing
>> ? ? ? ? a = (x + y) * z
>> let's just write
>> ? ? ? ? a = (x + y * z

> I'm glad you brought this up! How about this instead:

> a = x + y * z

> ...where the calculation is NOT subject to operator precedence? I
> always hated using parenthesis in mathematical calculations. All math
> should resolve in a linear fashion. 3+3*2 should always be 12 and NOT
> 9!

Doesn't matter.  At some point, somewhere, it would become desireable
to introduce precedence with (), at which point, it is quite possible
that the trailing ) would be redundant, so why not omit it?

> I am not trying to discredit you simply by disagreeing with you.

No, but you're certainly being insulting.

> I have offered facts as to why significant indention is far superior to
> braces and yet you continue to use the same emotionally charged babble
> in your defense.

Facts:
Pry your lips from Ritchie's left teet and stop slurping
that "brace" milk; because it is polluting your mind!

Emotionally charged babble:
My brain has quirks. Some people call them defects, some don't,
but it really doesn't matter; there are things about which
my brain is just plain unreliable and I rely moderately
heavily on extra visual cues to reduce the frequency with
which I get things wrong when skimming.

> When you offer some real facts then i will give then
> just consideration, until then i will "try" to enlighten you of the
> merits of significant indentation.

Well played!

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


Re: allow line break at operators

2011-08-12 Thread Seebs
On 2011-08-12, Chris Angelico  wrote:
> On Fri, Aug 12, 2011 at 5:33 PM, Seebs  wrote:
>> I've seen people in C do stuff like:

>> ? ? ? ?for (i = 0; i < N; ++i);
>> ? ? ? ? ? ? ? ?a[i] = 0;

>> This is clearly a case where indentation matches intent, but doesn't match
>> functionality, because C allows indentation to not-match functionality; this
>> is the famous problem Python is solving.

> There's several solutions to this. One is linting utilities that
> detect unexpectedly-indented code, which is the concept that Python
> took to the logical extent of syntactic errors. Another is (again
> linting) to disallow a direct trailing semicolon; if you want an empty
> body, you put whitespace before the semicolon.
>
> But that wasn't your point, I realise :)

I think it sort of is.  My current preference would be that C-like languages
would simply absolutely eliminate optional-braces.  Then the whole category
of errors would partially-go-away.  You could still have code which didn't
do what you meant, but it would be reliably easy to see what it did, and
so on.  But it's interesting to note that there are many ways to address
this.

Most of the C I've done has been in circumstances where misindented code
was in fact a thing that would fail reviews.

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


Re: Searching for Lottery drawing list of ticket match...

2011-08-12 Thread Miki Tebeka
It's the builtin "set", see 
http://docs.python.org/library/stdtypes.html#set-types-set-frozenset
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Problem reading HTTP_COOKIE

2011-08-12 Thread Jack Hatterly

> Date: Fri, 12 Aug 2011 21:29:25 +0100
> Subject: Re: Problem reading HTTP_COOKIE
> From: [email protected]
> To: [email protected]
> 
> I assume that what you mean is that it prints "None" even after you
> hit F5 to reload the page, as the first run of the script will never
> have a cookie.
> 
> Your script is now not actually setting any cookie. What cookie are
> you seeing in your browser? It may be something created and consumed
> by your framework, somewhere.

But my script *is* setting a cookie. I just sent a stripped-down version of the 
script earlier. Here's the entire script:

#! /usr/bin/python

import string
import os
import datetime, Cookie, random
import time
import os

def parse_cookie():
  ourTime = str(time.time())
  environ = os.environ
  cookie = environ.get('HTTP_COOKIE', '')
  if cookie == '':
cookie = string.replace(ourTime, '.', '')
cookie = Cookie.SimpleCookie()
expiration = datetime.datetime.now() + datetime.timedelta(days=30)
cookie['lastvisit'] = random.randint(1,)
cookie['lastvisit']['expires'] = 30 * 24 * 60 * 60
cookie['lastvisit']['path'] = '/var/www/html/my_site/clients/Millenium/'
cookie['lastvisit']['comment'] = random.randint(1,)
cookie['lastvisit']['domain'] = '.www.my_site.com'
cookie['lastvisit']['max-age'] = 30 * 24 * 60 * 60
cookie['lastvisit']['secure'] = ''
cookie['lastvisit']['version'] = 1
  c = Cookie.SimpleCookie()
  c.load(cookie)
  cookiedict = {}
  for key in c.keys():
cookiedict[key] = c.get(key).value
  print c
  print 'Content-Type: text/html\n'

  print ''
  print ''

if __name__ == "__main__":
  parse_cookie()

You see, every time when the cookie is read it comes back None which gets 
translated to '' and then the cookie is re-baked. *NOT* what I want!! I can see 
the cookie in my browser.
TIA,
Jack
  -- 
http://mail.python.org/mailman/listinfo/python-list


Re: Processing a large string

2011-08-12 Thread Dan Stromberg
This is the sort of thing I wrote bufsock for.  Don't let the name fool you
- although I originally wrote it for sockets,  it's since been extended to
work with files and file handles.

http://stromberg.dnsalias.org/~dstromberg/bufsock.html

It was recently modified to work on 2.x and 3.x.

On Thu, Aug 11, 2011 at 7:03 PM, goldtech  wrote:

> Hi,
>
> Say I have a very big string with a pattern like:
>
> akakksssk3dhdhdhdbddb3dkdkdkddk3dmdmdmd3dkdkdkdk3asnsn.
>
> I want to split the sting into separate parts on the "3" and process
> each part separately. I might run into memory limitations if I use
> "split" and get a big array(?)  I wondered if there's a way I could
> read (stream?) the string from start to finish and read what's
> delimited by the "3" into a variable, process the smaller string
> variable then append/build a new string with the processed data?
>
> Would I loop it and read it char by char till a "3"...? Or?
>
> Thanks.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-12 Thread Steven D'Aprano
Seebs wrote:

> On 2011-08-12, rantingrick  wrote:
>> What is with you guys and this need to have your hand held to read
>> code.
> 
> Good question!  Great to see that the helpful and welcoming community
> is living up to its reputation.

Please don't feed the troll. Responding to Rick's standard obnoxious posts
is like wrestling with a pig -- you get tired and filthy, you never
accomplish anything useful, and after a while, you realise that the pig is
enjoying it. Save yourself a lot of aggravation and kill-file him now.



-- 
Steven

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


Re: Java is killing me! (AKA: Java for Pythonheads?)

2011-08-12 Thread Dan Stromberg
Check varargs (as another poster mentioned), and consider doing your unit
tests in Jython.  Some shops that don't want Python for production code are
fine with Python for unit tests.

However, if the reason for preferring java is type checking, you could
perhaps get somewhere by suggesting pylint.

On Fri, Aug 12, 2011 at 10:02 AM, kj  wrote:

>
>
>
> *Please* forgive me for asking a Java question in a Python forum.
> My only excuse for this no-no is that a Python forum is more likely
> than a Java one to have among its readers those who have had to
> deal with the same problems I'm wrestling with.
>
> Due to my job, I have to port some Python code to Java, and write
> tests for the ported code.  (Yes, I've considered finding myself
> another job, but this is not an option in the immediate future.)
>
> What's giving me the hardest time is that the original Python code
> uses a lot of functions with optional arguments (as is natural to
> do in Python).
>
> As far as I can tell (admittedly I'm no Java expert, and have not
> programmed in it since 2001), to implement a Java method with n
> optional arguments, one needs at least 2**n method definitions.
> Even if all but one of these definitions are simple wrappers that
> call the one that does all the work, it's still a lot of code to
> wade through, for nothing.
>
> That's bad enough, but even worse is writing the unit tests for
> the resulting mountain of fluffCode.  I find myself writing test
> classes whose constructors also require 2**n definitions, one for
> each form of the function to be tested...
>
> I ask myself, how does the journeyman Python programmer cope with
> such nonsense?
>
> For the sake of concreteness, consider the following run-of-the-mill
> Python function of 3 arguments (the first argument, xs, is expected
> to be either a float or a sequence of floats; the second and third
> arguments, an int and a float, are optional):
>
>   def quant(xs, nlevels=MAXN, xlim=MAXX):
>if not hasattr(xs, '__iter__'):
>return spam((xs,), n, xlim)[0]
>
>if _bad_quant_args(xs, nlevels, xlim):
>raise TypeError("invalid arguments")
>
>retval = []
>for x in xs:
># ...
># elaborate acrobatics that set y
># ...
>retval.append(y)
>
>return retval
>
> My Java implementation of it already requires at least 8 method
> definitions, with signatures:
>
>short[] quant (float[], int, float)
>short[] quant (float[], int   )
>short[] quant (float[],  float)
>short[] quant (float[])
>
>short   quant (float  , int, float)
>short   quant (float  , int   )
>short   quant (float  ,  float)
>short   quant (float  )
>
> Actually, for additional reasons, too arcane to go into, I also
> need four more:
>
>short   quant (Float  , Integer, Float)
>short   quant (Float  , Integer   )
>short   quant (Float  ,  Float)
>short   quant (Float  )
>
> Writing JUnit tests for these methods is literally driving me
> INSANE.
>
> Some advice on implementing and testing functions with optional
> arguments in Java would be appreciated.
>
> TIA!
>
> kj
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-12 Thread Ben Finney
Seebs  writes:

> On 2011-08-12, rantingrick  wrote:
> > What is with you guys and this need to have your hand held to read
> > code.
>
> Good question!  Great to see that the helpful and welcoming community
> is living up to its reputation.

Please be aware that the particular person to whom you're responding is
decidedly not part of the helpful and welcoming community here.

> Man, you really love pushing them buttons, don't you?
>
> You don't understand a thing. Therefore... there is no such thing,
> anyone who experiences life differently from you needs to be insulted?

If you're interested, check the forum's archives for a thorough history
of what the helpful and welcoming community say about him. You'll find
we pretty much agree with your assessment.

-- 
 \  “Generally speaking, the errors in religion are dangerous; |
  `\those in philosophy only ridiculous.” —David Hume, _A Treatise |
_o__)   of Human Nature_, 1739 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-12 Thread Seebs
On 2011-08-12, Steven D'Aprano  wrote:
> Please don't feed the troll. Responding to Rick's standard obnoxious posts
> is like wrestling with a pig -- you get tired and filthy, you never
> accomplish anything useful, and after a while, you realise that the pig is
> enjoying it. Save yourself a lot of aggravation and kill-file him now.

You know...

I think I just realized where a big part of my misperception of the Python
community was.

Which is that until todayish, I had not realized that he was regarded as a
troll by the rest of the community.  But now that a couple of people have
told me this, I am a lot more comfortable referring to the Python community
in general as "welcoming".

I sometimes enjoy trying to extract information from people like that, but
I will respect the preferences of the actually-helpful people and drop that
line of inquiry.  :)

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


Re: Problem reading HTTP_COOKIE

2011-08-12 Thread Chris Angelico
I think the best thing to do would be to look at the raw headers. If
you can't do that in your framework, then try this: set the cookie,
shut down your server, fire up a debugging HTTP server on the same
port, and then refresh the page. If your browser is sending the
cookie, you'll see it in the HTTP request; if not, you have a
configuration issue.

As I said earlier, setting the cookie with a path like that may mean
that the browser won't send it.

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


Re: allow line break at operators

2011-08-12 Thread Ben Finney
Seebs  writes:

> I sometimes enjoy trying to extract information from people like that,
> but I will respect the preferences of the actually-helpful people and
> drop that line of inquiry. :)

Much appreciated, thank you :-)

-- 
 \  “It is well to remember that the entire universe, with one |
  `\   trifling exception, is composed of others.” —John Andrew Holmes |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-12 Thread Steven D'Aprano
Seebs wrote:

> You know, that's why the outdents-without-symbols bug me; I have a
> thing with a colon on it introducing something, and then there's nothing
> ending it.

But there is something ending it: a change in indentation level.

Python's parser explicitly pushes INDENT and OUTDENT tokens into the stream.
They're just a change of state in indentation level, which is much more
easily seen without the need for counting braces. Python's parser may need
to count tokens, but for the human reader merely needs to use its intuitive
and highly accurate ability to notice when things line up.

(Aside: this is why I dislike two-space indents. That's narrow enough to
make the "does this line up" detector subject to too many false positives.)

> I want that match so I can let the naive stack-depth-counter 
> off somewhere in my brain do its thing without leaving me with a huge
> feeling of unclosed blocks.

Yet another reason to consider brace languages harmful: they spoil the
user's intuitive grasp of intuition as grouping.

And it really is intuitive[1]:

http://okasaki.blogspot.com/2008/02/in-praise-of-mandatory-indentation-for.html

Historically, nearly all languages with braces pre-date the widespread
adoption of tools that think they can mangle whitespace with impunity. (I
would say that the reasons that the tools are broken is *because*
programmers have trained themselves to think that whitespace doesn't
matter -- ask most writers or artists and they would say *of course*
whitespace matters. The separation between elements is important -- perhaps
not quite as important as the elements themselves, but still important.)
Explicit BEGIN/END tokens exist to make the job of the parser easier, not
that of the programmer. But the human brain is a funny thing: you can train
it to expect to do more work than is necessary, and it will complain when
you make its job easier.



[1] For some definition of intuition.

-- 
Steven

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


Re: allow line break at operators

2011-08-12 Thread Chris Angelico
On Fri, Aug 12, 2011 at 11:39 PM, Steven D'Aprano
 wrote:
> ask most writers or artists and they would say *of course*
> whitespace matters.

You can write Perl code in the shape of a camel. Can you do that in Python?

Okay. Open challenge to anyone. Write a Python script that outputs
"Just another Python hacker" or some such message, and is shaped in
some way appropriately. And no fair doing all the shaping in comments
:)

(Has it already been done?)

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


RE: Problem reading HTTP_COOKIE

2011-08-12 Thread Jack Hatterly

Chris, I finally got a script that works. Thanks for trying!
Jack

#!/usr/bin/env python

import string
import os
import datetime, Cookie, random
import time

# The returned cookie is available in the os.environ dictionary
cookie_string = os.environ.get('HTTP_COOKIE')

if not cookie_string:
  ourTime = str(time.time())
  cookie = Cookie.SimpleCookie()
  cookie['lastvisit'] = string.replace(ourTime, '.', '')
  print cookie
  print 'Content-Type: text/html\n'
  print ''
  print 'Server time is', time.asctime(time.localtime()), ''
  # The first time the page is run there will be no cookies
  print 'First visit or cookies disabled'
  cookie = string.replace(ourTime, '.', '')
  cookie = Cookie.SimpleCookie()
  expiration = datetime.datetime.now() + datetime.timedelta(days=30)
  cookie['lastvisit'] = string.replace(ourTime, '.', '')
else: # Run the page twice to retrieve the cookie
  cookie = Cookie.SimpleCookie()
  cookie['lastvisit'] = cookie_string
  cookie['lastvisit']['expires'] = 30 * 24 * 60 * 60
  cookie['lastvisit']['path'] = '/cgi-bin/'
  cookie['lastvisit']['comment'] = 'holds the last user\'s visit date'
  cookie['lastvisit']['domain'] = '.www.my_site.com'
  cookie['lastvisit']['max-age'] = 30 * 24 * 60 * 60
  cookie['lastvisit']['secure'] = ''
  cookie['lastvisit']['version'] = 1
  print 'Content-Type: text/html\n'
  print '', cookie, ''
  for morsel in cookie:
print '', morsel, '=', cookie[morsel].value
print ''
for key in cookie[morsel]:
  print key, '=', cookie[morsel][key], ''
print ''


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


Re: Problem reading HTTP_COOKIE

2011-08-12 Thread Chris Angelico
On Fri, Aug 12, 2011 at 11:53 PM, Jack Hatterly
 wrote:
> cookie['lastvisit']['path'] = '/cgi-bin/'
>

Yep, that's looking a lot more useful!

Glad it's working.

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


Re: allow line break at operators

2011-08-12 Thread Ben Finney
Chris Angelico  writes:

> On Fri, Aug 12, 2011 at 11:39 PM, Steven D'Aprano
>  wrote:
> > ask most writers or artists and they would say *of course*
> > whitespace matters.
>
> You can write Perl code in the shape of a camel. Can you do that in
> Python?

I'm glad to be using a language where that sort of hard to-read code is
not encouraged by the syntax.

Art is wonderful, if you don't want to communicate clearly. I'll thank
the people who write the programs in my life to save their artistic
expression for areas where clear communication is optional.

-- 
 \   “My business is to teach my aspirations to conform themselves |
  `\  to fact, not to try and make facts harmonise with my |
_o__)   aspirations.“ —Thomas Henry Huxley, 1860-09-23 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-12 Thread Tim Chase

On 08/12/2011 05:50 PM, Chris Angelico wrote:

You can write Perl code in the shape of a camel. Can you do that in Python?

Okay. Open challenge to anyone. Write a Python script that outputs
"Just another Python hacker" or some such message, and is shaped in
some way appropriately. And no fair doing all the shaping in comments


Okay, my entry:

  print("Just another Python hacker")

That lovely one-line shape resembles a straight & narrow snake ;-)

-tkc


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


Re: allow line break at operators

2011-08-12 Thread Terry Reedy

On 8/12/2011 6:14 PM, Seebs wrote:

I am responding to your whole line of posts.

I have been indenting code neatly for at least 32 years whenever the 
language I used allowed it. Just over 14 years ago, when Python was an 
obscure little known or used languge, I adopted it *because* it dropped 
all the redundant bracket noise and looked to me like 'executable 
pseudocode', as I explained (with an unfortunate misspelling) in

https://groups.google.com/group/comp.lang.python/msg/cc25701a283a3f68
Indentation is part of that. Python-with-brackets would, to me, be 
something different -- sure, derived from Python, but not the same.


I do not need for you to adopt and use Python to validate my choice. If 
you like it fine, welcome. If not, have fun with something else. I said 
that over a decade when this same discussion took place, and I say it 
now. Different brains are different. I do not care which of us is in the 
majority in which population.


As I and others also pointed out over a decade ago, anyone is free to 
add insignificant comment braces (but keep that private, please) or, 
more sensibly, commented dedents to help the reader keep track of indent 
level.


for...
   for ...
  if ...
 for ...
if ...
   [50 more lines of code]
  #end outer if
  [more code]

--
Terry Jan Reedy

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


Re: generate and send mail with python: tutorial

2011-08-12 Thread Terry Reedy

On 8/12/2011 2:17 PM, aspineux wrote:

On Aug 12, 3:38 pm, Steven D'Aprano  wrote:

aspineux wrote:

Hi I have written a tutorial about how to generate and send emails
with python.


[...]

Thank you, that is an extremely detailed tutorial.


Thanks,  It was my intention


Have you considered contributing a HOW-TO?

--
Terry Jan Reedy

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


Re: allow line break at operators

2011-08-12 Thread Seebs
On 2011-08-12, Steven D'Aprano  wrote:
> Seebs wrote:
>> You know, that's why the outdents-without-symbols bug me; I have a
>> thing with a colon on it introducing something, and then there's nothing
>> ending it.

> But there is something ending it: a change in indentation level.

Hmm.

Okay, here's what I'm not getting.  Consider this:

if foo:
blah
if bar:
blah
blah

if baz:
blah
blah

> Python's parser explicitly pushes INDENT and OUTDENT tokens into the stream.

What's being pushed into the stream to indicate that the first outdent
is two outdents and the second is one?

I guess... The parser is explicitly pushing those tokens, but I can't
*SEE* those tokens.  If I am looking at the end of a really long
thing, and I see:

blah
blah

I only know what's happening if I have absolute confidence that the
indentation is always by the same amount, etectera.

> They're just a change of state in indentation level, which is much more
> easily seen without the need for counting braces. Python's parser may need
> to count tokens, but for the human reader merely needs to use its intuitive
> and highly accurate ability to notice when things line up.

Well, that's the thing.

In a case like:

if foo:
if bar:
blah
blah

I notice that *NOTHING* lines up with "if bar:".  And that affects me
about the way unmatched brackets do.

> (Aside: this is why I dislike two-space indents. That's narrow enough to
> make the "does this line up" detector subject to too many false positives.)

Yeah.

>> I want that match so I can let the naive stack-depth-counter 
>> off somewhere in my brain do its thing without leaving me with a huge
>> feeling of unclosed blocks.

> Yet another reason to consider brace languages harmful: they spoil the
> user's intuitive grasp of intuition as grouping.

I assume you mean "indentation as grouping".

I'm... not sold on this.  It's not that I don't see indentation as a kind
of grouping.  It's just that I really, really, want groups to have ends.

Consider the hypothetical array syntax:

a = [
1,
2
b = [
3,
4

This *bugs* me.  It's perfectly legible, and if you define it that way, it's
unambiguous and everything, but... It bugs me.  I want beginnings to have
an actual corresponding end.

> But the human brain is a funny thing: you can train
> it to expect to do more work than is necessary, and it will complain when
> you make its job easier.

Easier varies somewhat from person to person.  I need a LOT of parity checks
(speaking metaphorically) because my brain is fantastically prone to dropping
bits.  But I'm really fast.  So a thing with lots of parity checks is much
easier for me to actually *successfully* use than a thing which omits all
that extra stuff.

I was overjoyed when I saw that Ruby would let me write 1_048_576.  I can
read that with fewer errors than I can read 1048576.  (And yes, I could
also write "1<<20".)

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


Re: generate and send mail with python: tutorial

2011-08-12 Thread Ben Finney
Terry Reedy  writes:

> >> aspineux wrote:
> >>> Hi I have written a tutorial about how to generate and send emails
> >>> with python.

> Have you considered contributing a HOW-TO?

I think Terry is referring to http://docs.python.org/howto/>.

I agree that this should be submitted to that collection, and maintained
along with all the others.

What is the process if the OP, or someone to whom the OP delegates
authority, wants to do that?

-- 
 \“If you continue running Windows, your system may become |
  `\unstable.” —Microsoft, Windows 95 bluescreen error message |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-12 Thread Seebs
On 2011-08-13, Terry Reedy  wrote:
> I have been indenting code neatly for at least 32 years whenever the 
> language I used allowed it. Just over 14 years ago, when Python was an 
> obscure little known or used languge, I adopted it *because* it dropped 
> all the redundant bracket noise and looked to me like 'executable 
> pseudocode', as I explained (with an unfortunate misspelling) in
> https://groups.google.com/group/comp.lang.python/msg/cc25701a283a3f68
> Indentation is part of that. Python-with-brackets would, to me, be 
> something different -- sure, derived from Python, but not the same.

Fair enough.

> I do not need for you to adopt and use Python to validate my choice. If 
> you like it fine, welcome. If not, have fun with something else.

If this were among my options, it's probably what I'd do.  It is what I do
for things where I get a choice of languages.

FWIW, yes, I spec machines with ECC memory whenever I can.  I am a big
fan of "redundant" data that can detect likely errors.

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


Re: allow line break at operators

2011-08-12 Thread Ben Finney
Seebs  writes:

> What's being pushed into the stream to indicate that the first outdent
> is two outdents and the second is one?

See http://docs.python.org/reference/lexical_analysis.html> for a
comprehensive discussion of the lexing done on Python source.

To examine the resulting code objects, see the ‘dis’ module in the
standard library http://docs.python.org/library/dis.html>.

-- 
 \ “[T]he question of whether machines can think … is about as |
  `\ relevant as the question of whether submarines can swim.” |
_o__)  —Edsger W. Dijkstra |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: generate and send mail with python: tutorial

2011-08-12 Thread Ben Finney
Ben Finney  writes:

> What is the process if the OP, or someone to whom the OP delegates
> authority, wants to [contribute their work to the Python
> documentation]?

The answer is partly at http://docs.python.org/documenting/>:

If you’re interested in contributing to Python’s documentation […]
Send an e-mail to [email protected] or open an issue on the tracker.

One should, before doing so, follow the above document on the
documentation style conventions for Python.

-- 
 \  “Contentment is a pearl of great price, and whosoever procures |
  `\it at the expense of ten thousand desires makes a wise and |
_o__)  happy purchase.” —J. Balguy |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-12 Thread Gregory Ewing

Chris Angelico wrote:


But both of these violate XKCD 859.


For the benefit of all those who just went off to read
that strip, here's something to help you unwind:

)

There, you can relax now.

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


Re: allow line break at operators

2011-08-12 Thread Seebs
On 2011-08-13, Ben Finney  wrote:
> Seebs  writes:
>> What's being pushed into the stream to indicate that the first outdent
>> is two outdents and the second is one?

> See http://docs.python.org/reference/lexical_analysis.html> for a
> comprehensive discussion of the lexing done on Python source.

Interesting, thanks.

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


os.system() on Windows in Tkinter app spawns console window

2011-08-12 Thread Kevin Walzer
I'm developing a Tkinter app for a Windows customer, and the app bundles 
several command-line tools (ported from Unix). I call out to these 
console tools from the Tkinter app via os.system(). However, in the 
frozen version of my app, when I call out to these tools, I get multiple 
console windows popping up. This is jarring to say the least. Is there 
any way to run the commands under the hood without the console/DOS 
windows popping up?


--Kevin
--
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: 'Use-Once' Variables and Linear Objects

2011-08-12 Thread John Nagle

On 8/2/2011 7:19 AM, Neal Becker wrote:

I thought this was an interesting article

http://www.pipeline.com/~hbaker1/Use1Var.html


   Single-use was something of a dead end in programming.

   Single assignment, where you can only set a variable when you create
it, is more useful.  Single assignment is comparable to functional
programming, but without the deeply nested syntax.

   Functional programs are trees, while single-assignment programs are
directed acyclic graphs.  The difference is that you can fan-out
results, while in a a functional language, you can only fan in.
This fits well with Python, where you can write things like

   def fn(x) :
(a, b, c) = fn1()
return(fn2(a) + fn3(b)*c)

"const" is often used in C and C++ to indicate single-assignment usage.
But C/C++ doesn't have multiple return values, so the concept isn't as
useful as it is in Python.

Optimizing compilers usually recognize variable lifetimes, and so they
create single-assignment variables internally when possible.  This
is a win for register and stack allocation, and for fine-grain
parallelism on machines which support it.

Since Python isn't very optimizable, this is mostly a curiosity.

John Nagle

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


How to print non-printable chars??

2011-08-12 Thread Julio Cesar Rodriguez Cruz
Hi all,
If I open an .exe file in any text editor I get lot of odd chars,
what I want is to know how to output those chars if I have the hexadecimal
code. I found out how to do the reverse process with the quopri module,

i.e.:
>>> import quopri
>>> quopri.encodestring('ñè')
'=F1=E8=18'
>>> quopri.decodestring('=F1=E8=18')
'\xf1\xe8\x18'

but how to do the reverse? ...gived '\xf1\xe8\x18', print 'ñè'

any tips?
thanks
Julio Cesar
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.system() on Windows in Tkinter app spawns console window

2011-08-12 Thread Nobody
On Fri, 12 Aug 2011 22:49:32 -0400, Kevin Walzer wrote:

> I'm developing a Tkinter app for a Windows customer, and the app bundles 
> several command-line tools (ported from Unix). I call out to these 
> console tools from the Tkinter app via os.system(). However, in the 
> frozen version of my app, when I call out to these tools, I get multiple 
> console windows popping up. This is jarring to say the least. Is there 
> any way to run the commands under the hood without the console/DOS 
> windows popping up?

Just a wild guess, but try explicitly redirecting the commands'
stdin/stdout/stderr. You might also consider using subprocess.call()
instead of os.system().

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


Re: How to print non-printable chars??

2011-08-12 Thread Nobody
On Sat, 13 Aug 2011 00:59:42 -0400, Julio Cesar Rodriguez Cruz wrote:

> Hi all,
> If I open an .exe file in any text editor I get lot of odd chars,
> what I want is to know how to output those chars if I have the hexadecimal
> code. I found out how to do the reverse process with the quopri module,
> 
> i.e.:
 import quopri
 quopri.encodestring('ñè')
> '=F1=E8=18'
 quopri.decodestring('=F1=E8=18')
> '\xf1\xe8\x18'
> 
> but how to do the reverse? ...gived '\xf1\xe8\x18', print 'ñè'

print(quopri.decodestring('=F1=E8=18'))
or:
sys.stdout.write(quopri.decodestring('=F1=E8=18'))

If you type an expression into the interactive Python interpreter, the
result is converted to a string using repr(); for strings, this converts
8-bit characters to their hexadecimal escape sequences, so that the result
only uses ASCII.

OTOH, the print statement converts values to strings using str(); for
strings, this is an identity operation (i.e. it returns the original
string untouched). Similarly, the .write() method of file objects uses str().

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


Re: How to print non-printable chars??

2011-08-12 Thread Julio Cesar
On Aug 13, 1:22 am, Nobody  wrote:
> On Sat, 13 Aug 2011 00:59:42 -0400, Julio Cesar Rodriguez Cruz wrote:
>
> > Hi all,
> > If I open an .exe file in any text editor I get lot of odd chars,
> > what I want is to know how to output those chars if I have the hexadecimal
> > code. I found out how to do the reverse process with the quopri module,
>
> > i.e.:
>  import quopri
>  quopri.encodestring('ñè ')
> > '=F1=E8=18'
>  quopri.decodestring('=F1=E8=18')
> > '\xf1\xe8\x18'
>
> > but how to do the reverse? ...gived '\xf1\xe8\x18', print 'ñè '
>
>         print(quopri.decodestring('=F1=E8=18'))
> or:
>         sys.stdout.write(quopri.decodestring('=F1=E8=18'))
>
> If you type an expression into the interactive Python interpreter, the
> result is converted to a string using repr(); for strings, this converts
> 8-bit characters to their hexadecimal escape sequences, so that the result
> only uses ASCII.
>
> OTOH, the print statement converts values to strings using str(); for
> strings, this is an identity operation (i.e. it returns the original
> string untouched). Similarly, the .write() method of file objects uses str().

It just works!! thanks a lot and also for the explanations ;)
Cheers
Julio Cesar
-- 
http://mail.python.org/mailman/listinfo/python-list