Re: Simple programme - Just want to know whether this is correct way of coding

2009-05-08 Thread Lie Ryan

guptha wrote:

Hi group,
This is my first programme in python ,I need to know whether my code
is in the right path of performance

I wrote a code using multithreading to send mails


Can't you use BCC?


The code Works fine ,but I doubt about the performance issue ,My
intention is to send mails concurrently to large number of mail.
1.For every mail id i send It creates a new SMTP object,in case, if i
send to 1000 or more ids
  a) It obliviously creates that much SMPT connections ,is this a
right approach .
Thanks in Advance


In a lot of cases involving internet, the bottleneck would be internet 
speed. And for most purpose (except spamming) it is not really that 
necessary to send so much email in so little time (assuming you send 1 
mail per second -- which is really slow considering today's processor 
and internet speed -- you can send 86400 mails per day). Larger mailing 
list can also use BCC.

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


Re: Public attributes with really private data

2009-05-08 Thread Peter Otten
Mark Summerfield wrote:

> I had a quick search & didn't find anything _nice_ that produced
> attributes with really private data, so I came up with a possible
> solution---for Python 3.

Do really you think what you suggest below is "nice"?

By the way, your Attribute descriptor stores the value for all instances of 
A in the same variable...

Peter


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


Re: Python 2.6, File read() problems in Windows Xp

2009-05-08 Thread Dave Angel

Li Wang wrote:

Hi all:

I am trying to read a non-text file as a string by using Python
read(), however, it seems there is some thing wrong with it. I can use
read() on text file correctly, but unable to read .xls file correctly.
(The program can read any file correctly in Fedora 10)

Any idea how to solve this problem?

Thank you very much!

  
Chances are you forgot the "b" parameter to open().  Unnecessary in 
Unix, it tells the library to *not* translate \r\n  to \n upon read, or 
the inverse on write.  In other words, with the "b" parameter, the file 
is read in unchanged.


   infile = open(filename, "rb")
  


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


Re: SimpleXMLRPCServer and creating a new object on for each new client request.

2009-05-08 Thread Piet van Oostrum
> Jelle Smet  (JS) wrote:

One more thing:

>JS> I start python interactively:
> import xmlrpclib
> session1=xmlrpclib.ServerProxy('http://localhost:8000')
> session2=xmlrpclib.ServerProxy('http://localhost:8000')
> print session1.show_random()
>JS> 13930
> print session2.show_random()
>JS> 13930
> 

I get the impression, also from your use of the variable names
'session1' and 'session2' that xmlrpclib.ServerProxy() gives you some
kind of connection to the XMLRPC server. This is not the case. It gives
just an administration object *in the client* that will communicate with
the server when you call a method on it. The two session's in your code
are therefore functionally equivalent and there is no advantage in
having two of them instead of one. And the name session is misleading.

Please note also that XMLRPC isn't object-oriented. There is just the
server; in the protocol there are no objects other than the server.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: tkinter and widget placement after resizing

2009-05-08 Thread John Posner

jamieson wrote:

i.e. start out with a window like this:

[1][4][7]
[2][5][8]
[3][6][9]


make the main window larger and end up with this:

[1][6]
[2][7]
[3][8]
[4][9]
[5


Here's a solution, using Label widgets for clarity. The keys are:

* start numbering from zero, not one
* use divmod() on an item's index within the list to determine the 
item's column/row position

* bind the  event for window resizing

# redo_layout.py

import sys
from Tkinter import *

CHAR_WIDTH = 10
PAD = 3
INIT_COL_COUNT = 3

def grid_positions(count, numcols):
   """
   return a generator for (colnum, rownum) position tuples,
   given the total number of items and the number of columns

   the first column is filled with items, then the second, etc.
   """
   numrows, rem = divmod(count, numcols)
   # need an extra row if there was a remainder
   if rem:
   numrows += 1

   # return value is a generator
   return ( divmod(i, numrows) for i in range(count) )

def place_labels(event):
   """
   reposition all the items in the sequence "label_list"
   """
   # assumption: all labels have same width
   label_width = label_list[0].winfo_width()
   window_width = frm.winfo_width()

   # calculate new column count
   new_col_count = window_width // (label_width+PAD)

   # get new position iterator
   pos_iter = grid_positions(LABEL_COUNT, new_col_count)

   # redo layout
   for lab in label_list:
   lab.grid_forget()
   colnum, rownum = pos_iter.next()
   lab.grid(column=colnum, row=rownum, padx=PAD, pady=PAD)

def create_labels(count):
   """
   create a list of Label items,
   with text "1", "2", etc.
   """
   return [ Label(frm, bg='cyan', width=CHAR_WIDTH, text="%d" % i)
for i in range(count) ]

if __name__ == "__main__":
   try:
   LABEL_COUNT = int(sys.argv[1])
   except (ValueError, IndexError):
   print "ERROR: Must specify number of labels"
   sys.exit(1)

   # Tkinter window and whole-window Frame
   root = Tk()
   frm = Frame(root)
   frm.pack(expand=True, fill=BOTH)

   # create some labels
   label_list = create_labels(LABEL_COUNT)

   # perform initial layout
   pos_iter = grid_positions(LABEL_COUNT, INIT_COL_COUNT)
   for lab in label_list:
   coloff, rowoff = pos_iter.next()
   lab.grid(column=coloff, row=rowoff, padx=PAD, pady=PAD)
   del pos_iter

   # event configuration: redo the layout when the window size changes
   frm.bind('', place_labels)

   # go
   root.mainloop()

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


Re: Python 3.1 beta 1

2009-05-08 Thread pruebauno
On May 7, 11:57 am, bearophileh...@lycos.com wrote:
> >Equality tests between OrderedDict objects are order-sensitive and are 
> >implemented as list(od1.items())==list(od2.items()). Equality tests between 
> >OrderedDict objects and other Mapping objects are order-insensitive<
>
> very nice idea.
>

I don't know if somebody else is interested but I wouldn't mind
support to OrderedDict and namedtuple in the csv module:

Have csv.DictReader return an OrderedDict instead of a regular one
(based on the order of the column names in the header line).

Have csv.DictWriter accept an OrderedDict. That would take care of
this:

"Note that unlike the DictReader class, the fieldnames parameter of
the DictWriter is not optional. Since Python’s dict objects are not
ordered, there is not enough information available to deduce the order
in which the row should be written to the csvfile."
http://docs.python.org/dev/py3k/library/csv.html#csv.DictWriter

Add a new csv.NamedTupleReader and csv.NamedTupleWriter that work
similar to the DictReader and DictWriter then this snippet (in
examples 
http://docs.python.org/dev/py3k/library/collections.html#collections.namedtuple
):

EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title,
department, paygrade')
import csv
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv",
"rb"))):
print(emp.name, emp.title)

Could be rewritten as:

import csv
for emp in csv.NamedTupleReader("employees.csv"):
print(emp.name, emp.title)


Also, is there a way to convert a OrderedDict into a namedtuple? It is
possible to go the other direction using namedtuple._asdict, but I
don't see a _fromdict method.

And thanks Steven and Raymond for the Counter class. Several people
had started to see the common pattern and now we have it in the
stdlib.
--
http://mail.python.org/mailman/listinfo/python-list


About twisted.mail.smtp.SMTPDeliveryError

2009-05-08 Thread gganesh
hi group,
I wrote a code as below


from twisted.mail.smtp import sendmail
from twisted.internet import reactor
from twisted.python.log import err
import time

MAILSERVER = 'mail.xxx.com'
listTo = ['gxxx...@gmail.com', 'gjangox...@gmail.com',
'lxx...@yahoo.co.in', 'gk...@gmail.com']
FROM = 'ganes...@.com'
MSGBODY = "hi this final test"
a= time.time()
done = sendmail(MAILSERVER, FROM, listTo,
MSGBODY ,senderDomainName=None, port=25)
done.addErrback(err)
done.addCallback(lambda ignored: reactor.stop())
reactor.run()
print "Took %s seconds" %str(time.time()-a)



it showed me a error
like

"Failure: twisted.mail.smtp.SMTPDeliveryError: 554 No recipients
accepted"
and
"Relay access denied" errors

Is this error is because, i haven't
authenticated my email account to send mail.
Is so , having  username and password of smpt server ,how to
authenticate in
Twisted Framework

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


Re: What would YOU like to see in a txt to html converter?

2009-05-08 Thread Dotan Cohen
> I already thought of using dots or asterisks
> or whatever to let the user format the text instead of using html tags (this
> would be quite paradox ;-)
>

Then please do not invent another wheel. Write a markdown parser:
http://en.wikipedia.org/wiki/Markdown

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
--
http://mail.python.org/mailman/listinfo/python-list


Re: Public attributes with really private data

2009-05-08 Thread Carl Banks
On May 7, 11:37 pm, Mark Summerfield  wrote:
> Hi,
>
> I had a quick search & didn't find anything _nice_ that produced
> attributes with really private data, so I came up with a possible
> solution---for Python 3.
> (For Python 2 there does seem to be an approach although I'm not
> keen on 
> it:http://www.builderau.com.au/blogs/byteclub/viewblogpost.htm?p=339270875
> )
>
> Here's a standard class with one read-only and one writable
> property that has a tiny bit of validation.
>
> class P:
>     def __init__(self, w):
>         self.w = w
>     @property
>     def r(self): return 5
>     @property
>     def w(self): return self.__w
>     @w.setter
>     def w(self, value):
>         if value > 0: # Only +ve values allowed
>             self.__w = value
>         else:
>             raise ValueError("'{0}' is not valid for w".format(value))
>
> The read-only property is completely private because it isn't
> actually stored as such.
>
> But if we do dir() on an instance, in addition to 'r' and 'w', we
> also have '_P__w'. So the writable property's data is easily
> accessible, and the validation can be got around:
>
> >>> p = P(9)
> >>> p.r, p.w
> (5, 9)
> >>> p.w = 43
> >>> p.r, p.w
> (5, 43)
> >>> p.w = -7
>
> Traceback (most recent call last):
> ...
> ValueError: '-7' is not valid for w>>> p._P__w = -7
> >>> p.r, p.w
>
> (5, -7)
>
> Here's a class where I can't think of a way to access the private
> data and set invalid values.
>
> class A:
>     r = Attribute("r", 5)
>     w = Attribute("w", None, lambda self, value: value > 0)
>     def __init__(self, w):
>         self.w = w
>
> The Attribute class is a descriptor that takes three arguments:
> name of attribute, initial value (essential for read-only
> attributes!), and a validator function (which could be "lambda
> *a: True" if any value is accepatble).
>
> >>> a = A(9)
> >>> a.r, a.w
> (5, 9)
> >>> a.w = 43
> >>> a.r, a.w
> (5, 43)
> >>> a.w = -7
>
> Traceback (most recent call last):
> ...
> ValueError: '-7' is not valid for w
>
> If we do a dir(a) the only attributes we get (beyond those from
> object) are 'r' and 'w', so it shouldn't be possible to get
> around the validation---at least not easily.

Ok, I'll bite.

A.w = -7

A.__class__ = A_without_validation
a.w = -7

Attribute.__set__ = function_that_ignores_validation
a.w = -7


I am not opposed to adding a little well-considered protection to some
attributes where mistakes are prone to happen and/or dangerous, but it
is futile to try to stop access entirely.  There's just too many back
doors.

I would suggest that there really isn't much point in anything more
complex than your first solution, which was to validate with
properties and to store the value in a separate attribute.
Respectable programmers won't lightly bypass your validation if they
see that you've taken steps to enforce it.  OTOH, once a programmer,
respectable or not, decides to override your protection, they are not
likely to be stopped by something more complex.  So there is no point
in making it more complex.


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


Re: SQL and CSV

2009-05-08 Thread Peter Otten
Nick wrote:

> self.cursor = self.connection.cursor()
> first = True
> for row in reader:
> if first:
> headers = []
> for r in row:
> n = r.strip().replace (' ', '_').replace ('-','_')
> headers.append (n)
> command = 'create table csv (%s)' % ','.join (headers)
> self.cursor.execute (command)
> first = False
> else:
> command = 'insert into csv values ("%s")' % '","'.join
> (row)
> self.cursor.execute (command)
> 

You can simplify that a bit:

cursor = self.cursor = self.connection.cursor()

first_row = next(reader)
headers = [column.strip().replace(" ", "_").replace("-", "_") for column in 
first_row]
cursor.execute("create table csv (%s)" % ", ".join(headers))

placeholders = ", ".join("?"*len(headers))
command = "insert into csv values (%s)" % placeholders
cursor.executemany(command, reader)

While it may not matter here using placeholders instead of manually escaping 
user-provided values is a good habit to get into.

> self.cursor.execute (self.query)
> rows = self.cursor.fetchall()
  
rows = self.cursor.execute(self.query)

doesn't build an intermediate list.

> i = 0
> for row in rows:
> results.add (row, i)
> i = i + 1
 
This is written

for i, row in enumerate(rows):
results.add(row, i)

in idiomatic Python.

Peter

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


Re: Python 2.6, File read() problems in Windows Xp

2009-05-08 Thread Li Wang
2009/5/8 Chris Rebert :
> On Thu, May 7, 2009 at 10:04 PM, Li Wang  wrote:
>> Hi all:
>>

> the file, e.g. open("the_file.xls", "rb")
> Unlike *nix, Windows differentiates between binary and text files,
> hence the need for the "b" flag to specify which you're dealing with.

Hi
Thank you very much for reply,

The method doesn't work.
Here is the problem: after reading the whole fie as a string, I need
the string to be made of 8bits-symbols.

I do not mind what's the content in the file, what I need to do is
something like reading the file byte by byte and concatenate these
bytes into a single string.

Any suggestions?

Thank you very much





-- 
Li
--
Time is all we have
and you may find one day
you have less than you think
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6, File read() problems in Windows Xp

2009-05-08 Thread Li Wang
Hi:

Problem solved

Thank you very much, it works, It is my own problem:)

All the best,
Li

2009/5/8 Li Wang :
> 2009/5/8 Chris Rebert :
>> On Thu, May 7, 2009 at 10:04 PM, Li Wang  wrote:
>>> Hi all:
>>>
>
>> the file, e.g. open("the_file.xls", "rb")
>> Unlike *nix, Windows differentiates between binary and text files,
>> hence the need for the "b" flag to specify which you're dealing with.
>
> Hi
> Thank you very much for reply,
>
> The method doesn't work.
> Here is the problem: after reading the whole fie as a string, I need
> the string to be made of 8bits-symbols.
>
> I do not mind what's the content in the file, what I need to do is
> something like reading the file byte by byte and concatenate these
> bytes into a single string.
>
> Any suggestions?
>
> Thank you very much
>
>
>
>
>
> --
> Li
> --
> Time is all we have
> and you may find one day
> you have less than you think
>



-- 
Li
--
Time is all we have
and you may find one day
you have less than you think
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple programme - Just want to know whether this is correct way of coding

2009-05-08 Thread Dave Angel

guptha wrote:

Hi group,
This is my first programme in python ,I need to know whether my code
is in the right path of performance

I wrote a code using multithreading to send mails

FROM = 'com'

SUBJECT = 'This is the subject'
MSGBODY = 'This the body of the message '
MAILSERVER = 'mailcom'
port = 25
username = 'username'
password = 'pass'

# trim the strings of any leading or trailing spaces
FROM = FROM.strip()
SUBJECT = SUBJECT.strip()
MSGBODY = MSGBODY.strip()
MAILSERVER = MAILSERVER.strip()
username = username.strip()
password = password.strip()


# set up email parameters
msg = MIMEMultipart()
msg['From'] = FROM
msg['Subject'] = SUBJECT

#--
print "Starting Multi Thread Method"

class MyThread(Thread):

def __init__(self, site,  FROM, MSGBODY):
Thread.__init__(self)
self.site = site
self.FROM=FROM
self.MSGBODY=MSGBODY

def run(self):
#Connect to server
print 'Connecting to mail server ', MAILSERVER
try:
s = smtplib.SMTP(MAILSERVER,port)
print 'connected'
#s.set_debuglevel(1)
except:
print 'ERROR: Unable to connect to mail server', sys.exc_info   
()[0]
sys.exit(1)

#login to server
if password <> '':
print 'Logging into mail server'
try:
s.login(username,password)
except:
print 'ERROR: Unable to login to mail server', 
MAILSERVER
print 'Please recheck your password'
sys.exit(1)
print "running for %s " %self.site
print s
s.sendmail(self.FROM, self.site, self.MSGBODY)
print "from %s" %self.FROM
print "msg %s" %self.MSGBODY
print "Emailed for  site %s" %self.site
s.quit()
s.close()


a= time.time()
threads = []

for site in listTo:
T = MyThread(site,FROM,MSGBODY)
threads.append(T)
T.start()


for i in threads:
i.join()

print "Took %s seconds" %str(time.time()-a)

#-

The code Works fine ,but I doubt about the performance issue ,My
intention is to send mails concurrently to large number of mail.
1.For every mail id i send It creates a new SMTP object,in case, if i
send to 1000 or more ids
  a) It obliviously creates that much SMPT connections ,is this a
right approach .
Thanks in Advance

  
Any program that launches multiple threads is not a "simple program," 
especially for a first time user.


I don't know smtplib at all, so these questions may be off-base.  First, 
sendmail() takes as its second argument a list of to_addr, so why not 
send these all as a single operation?  If that would work, this would 
degenerate into a much simpler program.  More importantly, it should 
generate much less traffic between your machine and your smtp server, 
and probably less traffic between that server and the actual destination 
domains.  I have to assume that if it's a single sendmail request, the 
server would then batch-send them to each unique domain in the to_addrs 
list.Anyway, what if the message body be a couple of megabytes, and 
you're sending it to 100 people?  Sending a single message with a list 
in to_list would save tons of time.


Second, if you do have to send them all separately (for example, if you 
had different mail_options, which you don't yet), then I question the 
need or workability of using a separate thread for all of them.  Trying 
to open  1000 threads is very resource hungry,  Trying to open that many 
smtp connections is even worse.  One of these is likely to fail.  And 
I'm guessing that beyond 10 or so, it'd run at least as fast with a 
different approach.



If I had to do something like this, I'd expect to wind up with some 
number (say 10) of threads, and a queue of things for them to do.  So if 
you had 1000 things, each thread would do approximately 100 of them.  
Now, sharing a queue like that is more work, with more things to mess 
up.  Currently your threads share only read-only data, which makes 
threads pretty straightforward.



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


Re: Python 2.6, File read() problems in Windows Xp

2009-05-08 Thread Li Wang
Hi  Dave:
Thank you very much for you explanation:)


> Chances are you forgot the "b" parameter to open().  Unnecessary in Unix, it
> tells the library to *not* translate \r\n  to \n upon read, or the inverse
> on write.  In other words, with the "b" parameter, the file is read in
> unchanged.

So, if I am using python in Linux, do open('file', 'r') and
open('file', 'rb') work the same way?

Thanks,

Best regards,
Li
--
http://mail.python.org/mailman/listinfo/python-list


xml in python

2009-05-08 Thread Rustom Mody
Can someone give me a heads up on xml parsing in python?
The context is that I want to write a simple docbook to text converter.
DOM is alright -- dont want to break my head with SAX just for performance
when my documents are not likely to be large.

My problem is that there seems to be so many nearly equivalent ways (Pyxml?
Amara?) some of which have moved from 3rd party to builtin status that I am
not clear what is the current method of choice.

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


Re: SimpleXMLRPCServer and creating a new object on for each new client request.

2009-05-08 Thread Piet van Oostrum
> Piet van Oostrum  (PvO) wrote:

> Jelle Smet  (JS) wrote:
>PvO> One more thing:

>JS> I start python interactively:
> import xmlrpclib
> session1=xmlrpclib.ServerProxy('http://localhost:8000')
> session2=xmlrpclib.ServerProxy('http://localhost:8000')
> print session1.show_random()
>JS> 13930
> print session2.show_random()
>JS> 13930
> 

>PvO> I get the impression, also from your use of the variable names
>PvO> 'session1' and 'session2' that xmlrpclib.ServerProxy() gives you some
>PvO> kind of connection to the XMLRPC server. 

This should have been: I get the impression, also from your use of the
variable names 'session1' and 'session2', *that you think* that
xmlrpclib.ServerProxy() gives you some kind of connection to the XMLRPC
server.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple programme - Just want to know whether this is correct way of coding

2009-05-08 Thread Piet van Oostrum
> guptha  (g) wrote:

>g> Hi group,
>g> This is my first programme in python ,I need to know whether my code
>g> is in the right path of performance

>g> I wrote a code using multithreading to send mails

>g> FROM = 'com'

>g> SUBJECT = 'This is the subject'
>g> MSGBODY = 'This the body of the message '
>g> MAILSERVER = 'mailcom'
>g> port = 25
>g> username = 'username'
>g> password = 'pass'

>g> # trim the strings of any leading or trailing spaces
>g> FROM = FROM.strip()
>g> SUBJECT = SUBJECT.strip()
>g> MSGBODY = MSGBODY.strip()
>g> MAILSERVER = MAILSERVER.strip()
>g> username = username.strip()
>g> password = password.strip()


>g> # set up email parameters
>g> msg = MIMEMultipart()
>g> msg['From'] = FROM
>g> msg['Subject'] = SUBJECT

>g> #--
>g> print "Starting Multi Thread Method"

>g> class MyThread(Thread):

>g> def __init__(self, site,  FROM, MSGBODY):
>g> Thread.__init__(self)
>g> self.site = site
>g> self.FROM=FROM
>g> self.MSGBODY=MSGBODY

>g> def run(self):
>g> #Connect to server
>g> print 'Connecting to mail server ', MAILSERVER
>g> try:
>g> s = smtplib.SMTP(MAILSERVER,port)
>g> print 'connected'
>g> #s.set_debuglevel(1)
>g> except:
>g> print 'ERROR: Unable to connect to mail server', sys.exc_info   
>()[0]
>g> sys.exit(1)

>g> #login to server
>g> if password <> '':
>g> print 'Logging into mail server'
>g> try:
>g> s.login(username,password)
>g> except:
>g> print 'ERROR: Unable to login to mail server', 
>MAILSERVER
>g> print 'Please recheck your password'
>g> sys.exit(1)
>g> print "running for %s " %self.site
>g> print s
>g> s.sendmail(self.FROM, self.site, self.MSGBODY)
>g> print "from %s" %self.FROM
>g> print "msg %s" %self.MSGBODY
>g> print "Emailed for  site %s" %self.site
>g> s.quit()
>g> s.close()


>g> a= time.time()
>g> threads = []

>g> for site in listTo:
>g> T = MyThread(site,FROM,MSGBODY)
>g> threads.append(T)
>g> T.start()


>g> for i in threads:
>g> i.join()

>g> print "Took %s seconds" %str(time.time()-a)

>g> #-

Tuesday this same program with some minor differences was posted by
gganesh . There was a discussion about that. So
did you copied that program with the suggested changes? I don't think it
is nice to have two parallel discussions on the same subject. And
copying without giving credits is not considered nice behaviour either.
Usually it is called plagiarism.

>g> The code Works fine ,but I doubt about the performance issue ,My
>g> intention is to send mails concurrently to large number of mail.
>g> 1.For every mail id i send It creates a new SMTP object,in case, if i
>g> send to 1000 or more ids
>g>   a) It obliviously creates that much SMPT connections ,is this a
>g> right approach .

For such a big number of mails this is not the right approach. First
your operating system may not like it to have such a large number of
threads active. Second, the mail server probably doesn't like it that
you make such a large number of connections simultaneously. If the mail
server doesn't protest, probably its systems administrator will.
Moreover there is probably no benefit in having 1000 connections open to
the same mail server because long before there will be another
bottleneck such as your network connection or the CPU load of either
your computer or the mail server, unless you are on a very scalable
infrastructure.

A better solution will be to use a Thread Pool with a limited number of
simultaneous threads (my guess is that 10-20 or so would be good
enough).

And as I said to my students yesterday: You shouldn't program
multithreaded applications unless you have studied this subject
thoroughly. Of course I don't know how this applies to you.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Which python version do I use with "virtualenv"?

2009-05-08 Thread OldGrantonian
On May 7, 9:33 pm, Duncan Booth  wrote:
> OldGrantonian  wrote:
> > Where do I find the win32 extensions?
>
> http://www.google.com/search?q=python+win32
>
> Any of the first 4 hits should help.

Success :)

Many thanks to all responders in this thread :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Which python version do I use with "virtualenv"?

2009-05-08 Thread OldGrantonian
On May 7, 9:33 pm, Duncan Booth  wrote:
> OldGrantonian  wrote:
> > Where do I find the win32 extensions?
>
> http://www.google.com/search?q=python+win32
>
> Any of the first 4 hits should help.

Success :)

Many thanks to all responders in this thread :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newcomer to Python tutorial question

2009-05-08 Thread Alan Cameron
"Terry Reedy"  wrote in message 
news:mailman.5248.1241732704.11746.python-l...@python.org...
> Alan Cameron wrote:
>>
> why is the printed result of
>
 basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
 print(basket)
> {'orange', 'banana', 'pear', 'apple'}
>
> in the sequence given?
>
>> It appears that I used a reserved term when I used 'sequence'.
>
> No and Sort-of.
>
> No: We often use it in the normal English sense of ordered items, as I and 
> I think others assume you did.  Your question is quite legitimate, and the 
> answer, as indicated, is how an implementation interacts with the sequence 
> of additions.
>
> Sort-of: The library manual section of Sequence Types lists the sequence 
> operations common to all or most built-in Python sequence classes.  But it 
> does not explicitly define sequence.  Ranges, which are iterables that 
> directly support only indexing and len(), are called sequences. Dicts, 
> which are iterables that support len() but are usually not indexed by 
> integers, are not.  So that suggests a minimal definition of sequence, but 
> all the other sequence classes support much more that is typically 
> assumed.
>
> Keywords are reserved terms in the language such as 'if' and 'None' that 
> are specially recognized by the parser and which affect compilation. 
> Identifiers of the form '__x...y__' are reserved names.  Non-terminal 
> terms in the grammar are reserved terms, in a sense, within the reference 
> manual, but 'expression_list', not 'sequence', is used for comma-separated 
> sequences of expressions in code.  The comma-separated sequence of items 
> in a function call is separately defined as an 'argument_list' because 
> 'keyword_item's like 'a=b' and '*' and '**' are not expressions and 
> because there are some order restrictions on argument items.
>
> Terry Jan Reedy
>

Thanks for the explanation.

In particular reference to the tutorial section
http://docs.python.org/3.0/tutorial/datastructures.html#nested-list-comprehensions

There is a word which is ambiguous, at least to me.

Perhaps you can explain the use of the word 'comprehensions'.

Comprehension I understand
Comprehensions I don't.

Is there a glossary of terms somewhere?

-- 
Alan Cameron 


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


Creating temperory files for a web application

2009-05-08 Thread koranthala
Hi,
   I am doing web development using Django. I need to create an image
(chart) and show it to the users - based on some data which user
selects.
   My question is - how do I create a temporary image for the user? I
thought of tempfile, but I think it will be deleted once the process
is done - which would happen by the time user starts seeing the image.
I can think of no other option other than to have another script which
will delete all images based on time of creation.
   Since python is extensively used for web development, I guess this
should be an usual scenario for many people here. How do you usually
handle this?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Web Based Front End?

2009-05-08 Thread Jeremiah Dodds
On Fri, May 8, 2009 at 2:52 AM,  wrote:

> So, my question is what is the best method to be able to have a user
> enter specific data on a web page, have that data be passed to the
> Python script and then have the output returned to the web page?
> Essentially, I want to use a web based front end to accomplish the
> same thing that the IDLE GUI does, (asks me a few questions, I answer
> them, it builds a configuration file and prints it to the screen).
>
>
There isn't a best way, really.

I'm partial to CherryPy. A minimal example would look like so:

---
import cherrypy

class Root(object):
page = "%s"
@cherrypy.expose
def enter_data(self, data):
return self.page % ("You entered: " + data,)

@cherrypy.expose
def index(self):
form = """

  Enter some stuff here
  

"""
return self.page % form

if __name__ == '__main__':
cherrypy.quickstart(Root())

---

Note, I wouldn't actually recommend using string building like that for
returning pages unless your app is seriously trivial. I use Genshi for
templating, the tutorial that they have is very nice (and uses cherrypy).

There's a plethora of different ways to build web apps in python. In all
reality, you should probably try out a few and see what suits your tastes.
--
http://mail.python.org/mailman/listinfo/python-list


Re: heapq.merge with key=

2009-05-08 Thread bearophileHUGS
Looking for this, Kevin D. Smith?
http://code.activestate.com/recipes/502295/

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Creating temperory files for a web application

2009-05-08 Thread Diez B. Roggisch
koranthala wrote:

> Hi,
>I am doing web development using Django. I need to create an image
> (chart) and show it to the users - based on some data which user
> selects.
>My question is - how do I create a temporary image for the user? I
> thought of tempfile, but I think it will be deleted once the process
> is done - which would happen by the time user starts seeing the image.

What makes you think that? You are the one creating it, you are responsible
for deleting it.

> I can think of no other option other than to have another script which
> will delete all images based on time of creation.
>Since python is extensively used for web development, I guess this
> should be an usual scenario for many people here. How do you usually
> handle this?

There are various solutions - tempfiles, files based on a criteria (e.g.
username and image-properties) so that they don't pollute the harddrive.

For both approaches cleaning up as you suggest might be needed.

Alternatively, if you use sessions, you can use memory-cached images.

Or you can use the database.

But the cleaning-up might get necessary here as well.

The cleanest solution would be if the image would be rendered on the fly,
based on GET-parameters (or REST-ful urls) so that you can render it into
memory as string, but then forget immediately about it.

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


php to python code converter

2009-05-08 Thread bvidinli
if anybody needs:
http://code.google.com/p/phppython/
--
http://mail.python.org/mailman/listinfo/python-list


Compiling snippets of python code

2009-05-08 Thread Basil Brush

I need some advice on compiling snippets of python source at runtime. So
perhaps some python experts can point the way.

I am rewriting an old Java app in python. It tries to find solutions to
computational problems based on the idea of genetic evolution. The Java
version just used an array of bytes for the genomes. These byte
sequences were bytecode which told a rudimentary VM (virtual machine)
which maths functions to call. It used another array as a small chunk of
virtual memory for doing the calculations.

Having seen the docs on python's compile module, I'm thinking of doing
it differently in the new python version. My aim is to have the genomes
made up of a sequence of python source snippets, with each snippet to be
randomly generated, compiled, and executed at runtime. The advantage of
this is that it gives me greater flexibility and I can change what
actions the genomes can do without having to add new functions to my VM.

But there's some crucial points. When the snippet is executed I would
need to pass in a list or array, and I need the list back again with any
changes that were made; this is the virtual memory and how I would get
the results back, and is also how the snippet would get data from a
previous snippet in a sequence. How would I do this? Also, there is a
database of input data. Rather than pass all that data to the snippet
I'd rather have functions in my module which the snippet could call to
get data. So what's the scope of an executing piece of code? Can it
access my modules and functions?

My linux system has python 2.5 and I noticed that the docs say the
compile module has been removed from python 3.0. So I'm concerned about
whether my app would work in 3.0 if I upgraded. Does anyone know if they
moved the compiler to another module or simply removed it entirely?
--
http://mail.python.org/mailman/listinfo/python-list


Re: IIR filter conversion routines for Python?

2009-05-08 Thread Lawrence D'Oliveiro
In message , wzab wrote:

> I'm looking for procedures converting the IIR filters into cascade and/
> or parallel forms.

Tried a DSP textbook?

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


Re: SQL and CSV

2009-05-08 Thread Lawrence D'Oliveiro
In message , Peter Otten wrote:

> While it may not matter here using placeholders instead of manually
> escaping user-provided values is a good habit to get into.

Until you hit things it can't deal with.

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


How do I test the integrity of a Python installation in Debian and Ubuntu

2009-05-08 Thread Geoff Gardiner
How do I assure myself of the integrity of a Python installation
acquired using apt-get install on Debian and Ubuntu?

I can run regrtest but there's nothing in the basic installation to run,
viz.:

geg...@gegard:~$ python
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from test import regrtest
>>> regrtest.main()
test_grammar
test_grammar skipped -- No module named test_grammar
...  more of the same...
9 tests skipped:
test_builtin test_doctest test_doctest2 test_exceptions
test_grammar test_opcodes test_operations test_types test_unittest
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.5/test/regrtest.py", line 416, in main
e = _ExpectedSkips()
  File "/usr/lib/python2.5/test/regrtest.py", line 1321, in __init__
from test import test_socket_ssl
ImportError: cannot import name test_socket_ssl
>>>

I don't see where to go from here, so advice would be extremely helpful.

Background

I have a large Python-based system that I am trying to install on an
externally-hosted VM. It doesn't build and install correctly most of the
time, and I have tried successive images of Debian Lenny and Ubuntu
Hardy with mostly different build/installation results each time.

The installation proceeds Ok on a local Ubuntu VM.

A number of modules are installed in addition to python, but I can't
even see how to test the core python installation. There are few
test_*.py files in the installation.

I have previously encountered a fault on the server hosting the VM and
would like to be more comfortable that the python installation itself is
Ok (or have evidence that it's not).

Thank you,
Geoff

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


String.Template Source ...

2009-05-08 Thread Mic Pringle
Hi,

I'd like to have a 'dig around' in the source for String.Template, but
can't seem to find where it lives.

Could someone please let me know where about's in the source (perhaps
a path?) the template functions live ?

I'm working on a Mac, using Leopard and the bundled version of Python.

Thanks

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


Re: Creating temperory files for a web application

2009-05-08 Thread koranthala
On May 8, 2:49 pm, "Diez B. Roggisch"  wrote:
> koranthala wrote:
> > Hi,
> >    I am doing web development using Django. I need to create an image
> > (chart) and show it to the users - based on some data which user
> > selects.
> >    My question is - how do I create a temporary image for the user? I
> > thought of tempfile, but I think it will be deleted once the process
> > is done - which would happen by the time user starts seeing the image.
>
> What makes you think that? You are the one creating it, you are responsible
> for deleting it.
>
> > I can think of no other option other than to have another script which
> > will delete all images based on time of creation.
> >    Since python is extensively used for web development, I guess this
> > should be an usual scenario for many people here. How do you usually
> > handle this?
>
> There are various solutions - tempfiles, files based on a criteria (e.g.
> username and image-properties) so that they don't pollute the harddrive.
>
> For both approaches cleaning up as you suggest might be needed.
>
> Alternatively, if you use sessions, you can use memory-cached images.
>
> Or you can use the database.
>
> But the cleaning-up might get necessary here as well.
>
> The cleanest solution would be if the image would be rendered on the fly,
> based on GET-parameters (or REST-ful urls) so that you can render it into
> memory as string, but then forget immediately about it.
>
> Diez

Thank you Diez.
I would like to go ahead with the cleanest solution indeed.
I am creating the image on the fly. But I could not understand what
you meant by render to memory as a string.
How do we send the image to the browser?

Were you mentioning about having the image as a string and then
passing to the browser based on data URL scheme  ?
Or is it something else like XBM format or something? I am sorry - but
I am quite unsure of what you meant?

I am actually creating PDFs, CSVs and images on the fly. So, I need to
delete them all after that.
The images can be somewhat large - ~2MB. The RFC mentions that large
data cannot be sent that way.

Is it that I will have to delete the images using a separate script
later?

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


Re: String.Template Source ...

2009-05-08 Thread Peter Otten
Mic Pringle wrote:

> I'd like to have a 'dig around' in the source for String.Template, but
> can't seem to find where it lives.

I assume that you mean string.Template.

> Could someone please let me know where about's in the source (perhaps
> a path?) the template functions live ?
> 
> I'm working on a Mac, using Leopard and the bundled version of Python.

Import the module and inspect its __file__ attribute:

>>> import string
>>> string.__file__
'/usr/lib/python2.6/string.pyc'

This means that the string module's path is /usr/lib/python2.6/string.py 
over here.

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


Re: String.Template Source ...

2009-05-08 Thread Mic Pringle
Brilliant, thanks Peter.

-Mic

2009/5/8 Peter Otten <__pete...@web.de>:
> Mic Pringle wrote:
>
>> I'd like to have a 'dig around' in the source for String.Template, but
>> can't seem to find where it lives.
>
> I assume that you mean string.Template.
>
>> Could someone please let me know where about's in the source (perhaps
>> a path?) the template functions live ?
>>
>> I'm working on a Mac, using Leopard and the bundled version of Python.
>
> Import the module and inspect its __file__ attribute:
>
 import string
 string.__file__
> '/usr/lib/python2.6/string.pyc'
>
> This means that the string module's path is /usr/lib/python2.6/string.py
> over here.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Public attributes with really private data

2009-05-08 Thread Mark Summerfield
On 8 May, 08:19, Peter Otten <__pete...@web.de> wrote:
> MarkSummerfieldwrote:
> > I had a quick search & didn't find anything _nice_ that produced
> > attributes with really private data, so I came up with a possible
> > solution---for Python 3.
>
> Do really you think what you suggest below is "nice"?

Well the code isn't ugly and doesn't mess with the call stack etc.

> By the way, your Attribute descriptor stores the value for all instances of
> A in the same variable...

It seems like it does, but it doesn't. The hidden_value is an instance
variable that is created every time an Attribute object is created.

>>> from Attribute import *
>>> class A:
a = Attribute("a", 5, lambda *a: True)
b = Attribute("b", 5, lambda *a: True)
>>> class B:
a = Attribute("a", 5, lambda *a: True)
b = Attribute("b", 5, lambda *a: True)
>>> a = A()
>>> b = B()
>>> a.a,a.b,b.a,b.b
(5, 5, 5, 5)
>>> a.a=1;a.b=2;b.a=3;b.b=4
>>> a.a,a.b,b.a,b.b
(1, 2, 3, 4)

--
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
C++, Python, Qt, PyQt - training and consultancy
"Programming in Python 3" - ISBN 0137129297
--
http://mail.python.org/mailman/listinfo/python-list


Re: Creating temperory files for a web application

2009-05-08 Thread koranthala
On May 8, 5:22 pm, koranthala  wrote:
> On May 8, 2:49 pm, "Diez B. Roggisch"  wrote:
>
>
>
> > koranthala wrote:
> > > Hi,
> > >    I am doing web development using Django. I need to create an image
> > > (chart) and show it to the users - based on some data which user
> > > selects.
> > >    My question is - how do I create a temporary image for the user? I
> > > thought of tempfile, but I think it will be deleted once the process
> > > is done - which would happen by the time user starts seeing the image.
>
> > What makes you think that? You are the one creating it, you are responsible
> > for deleting it.
>
> > > I can think of no other option other than to have another script which
> > > will delete all images based on time of creation.
> > >    Since python is extensively used for web development, I guess this
> > > should be an usual scenario for many people here. How do you usually
> > > handle this?
>
> > There are various solutions - tempfiles, files based on a criteria (e.g.
> > username and image-properties) so that they don't pollute the harddrive.
>
> > For both approaches cleaning up as you suggest might be needed.
>
> > Alternatively, if you use sessions, you can use memory-cached images.
>
> > Or you can use the database.
>
> > But the cleaning-up might get necessary here as well.
>
> > The cleanest solution would be if the image would be rendered on the fly,
> > based on GET-parameters (or REST-ful urls) so that you can render it into
> > memory as string, but then forget immediately about it.
>
> > Diez
>
> Thank you Diez.
> I would like to go ahead with the cleanest solution indeed.
> I am creating the image on the fly. But I could not understand what
> you meant by render to memory as a string.
> How do we send the image to the browser?
>
> Were you mentioning about having the image as a string and then
> passing to the browser based on data URL scheme  ?
> Or is it something else like XBM format or something? I am sorry - but
> I am quite unsure of what you meant?
>
> I am actually creating PDFs, CSVs and images on the fly. So, I need to
> delete them all after that.
> The images can be somewhat large - ~2MB. The RFC mentions that large
> data cannot be sent that way.
>
> Is it that I will have to delete the images using a separate script
> later?

Hi Diez,
   I think I understood your point now.
   Is it ?
   (1) Have a separate URL for the image - update urls.py for that
   (2) Pass all the GET parameters to that URL again.
   (3) Recalculate the fields again in that URL
   (4) Create the image and send back as image/png based on the
received fields.
   Other than the fact that I will be hitting the DB twice - for the
fields in the original URL and for creating Image in the second URL, I
think this is the best option.
   Please let me know whether I have understood correctly.

   The same option can be done for CSV and PDF files too. Thank you
very much Diez.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Public attributes with really private data

2009-05-08 Thread Mark Summerfield
On 8 May, 09:52, Carl Banks  wrote:
> On May 7, 11:37 pm, MarkSummerfield wrote:
>
>
>
> > Hi,
>
> > I had a quick search & didn't find anything _nice_ that produced
> > attributes with really private data, so I came up with a possible
> > solution---for Python 3.
> > (For Python 2 there does seem to be an approach although I'm not
> > keen on 
> > it:http://www.builderau.com.au/blogs/byteclub/viewblogpost.htm?p=339270875
> > )
>
> > Here's a standard class with one read-only and one writable
> > property that has a tiny bit of validation.
>
> > class P:
> >     def __init__(self, w):
> >         self.w = w
> >     @property
> >     def r(self): return 5
> >     @property
> >     def w(self): return self.__w
> >     @w.setter
> >     def w(self, value):
> >         if value > 0: # Only +ve values allowed
> >             self.__w = value
> >         else:
> >             raise ValueError("'{0}' is not valid for w".format(value))
>
> > The read-only property is completely private because it isn't
> > actually stored as such.
>
> > But if we do dir() on an instance, in addition to 'r' and 'w', we
> > also have '_P__w'. So the writable property's data is easily
> > accessible, and the validation can be got around:
>
> > >>> p = P(9)
> > >>> p.r, p.w
> > (5, 9)
> > >>> p.w = 43
> > >>> p.r, p.w
> > (5, 43)
> > >>> p.w = -7
>
> > Traceback (most recent call last):
> > ...
> > ValueError: '-7' is not valid for w>>> p._P__w = -7
> > >>> p.r, p.w
>
> > (5, -7)
>
> > Here's a class where I can't think of a way to access the private
> > data and set invalid values.
>
> > class A:
> >     r = Attribute("r", 5)
> >     w = Attribute("w", None, lambda self, value: value > 0)
> >     def __init__(self, w):
> >         self.w = w
>
> > The Attribute class is a descriptor that takes three arguments:
> > name of attribute, initial value (essential for read-only
> > attributes!), and a validator function (which could be "lambda
> > *a: True" if any value is accepatble).
>
> > >>> a = A(9)
> > >>> a.r, a.w
> > (5, 9)
> > >>> a.w = 43
> > >>> a.r, a.w
> > (5, 43)
> > >>> a.w = -7
>
> > Traceback (most recent call last):
> > ...
> > ValueError: '-7' is not valid for w
>
> > If we do a dir(a) the only attributes we get (beyond those from
> > object) are 'r' and 'w', so it shouldn't be possible to get
> > around the validation---at least not easily.
>
> Ok, I'll bite.
>
> A.w = -7
>
> A.__class__ = A_without_validation
> a.w = -7
>
> Attribute.__set__ = function_that_ignores_validation
> a.w = -7

I don't see how that can work? Sure you could replace the __set__
method, or the Attribute.__setter method. But neither can actually
change the hidden_value because AFAIK that only exists within the
scope of a closure and so isn't accesssible. (Well, maybe if you
started using the inspect module you'd find it.)

> I am not opposed to adding a little well-considered protection to some
> attributes where mistakes are prone to happen and/or dangerous, but it
> is futile to try to stop access entirely.  There's just too many back
> doors.

Sure, but I like the fact that there is no "shadow" attribute, so just
"w" not "w" _and_ "_A__w".

> I would suggest that there really isn't much point in anything more
> complex than your first solution, which was to validate with
> properties and to store the value in a separate attribute.
> Respectable programmers won't lightly bypass your validation if they
> see that you've taken steps to enforce it.  OTOH, once a programmer,
> respectable or not, decides to override your protection, they are not
> likely to be stopped by something more complex.  So there is no point
> in making it more complex.
>
> Carl Banks

I think that's a fair viewpoint, but I still like the idea of there
being no _A__w available for property w.

--
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
C++, Python, Qt, PyQt - training and consultancy
"Programming in Python 3" - ISBN 0137129297
--
http://mail.python.org/mailman/listinfo/python-list


Re: SQL and CSV

2009-05-08 Thread andrew cooke
Lawrence D'Oliveiro wrote:
> In message , Peter Otten wrote:
>
>> While it may not matter here using placeholders instead of manually
>> escaping user-provided values is a good habit to get into.
>
> Until you hit things it can't deal with.

The post you are replying to was talking about using the SQL library's "?"
syntax that automatically escapes values.  The usual reason this is
recommended (if I have understood correctly) is that the library code is
much more likely to foil injection attacks.  I have seen this mentioned
often and assume it is good advice.

Can you expand on your comment?  I assume you are thinking of how the
library might handle some strange class.  But aren't the number of types
limited by SQL?  In which case a "thing that can't be handled" could
presumably be managed by adding an appropriate __str__ or __float__ or
whatever?  And you would still use the library to give safety with other
values.

Maybe you could give an example of the kind of problem you're thinking of?

Thanks,
Andrew



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


Re: Which one is best Python or Java for developing GUI applications?

2009-05-08 Thread Pascal Chambon




On Thu, May 7, 2009 at 1:42 PM, Pascal Chambon 
mailto:chambon.pas...@wanadoo.fr>> wrote:


   Hello

   When a lot of code using wxwidgets is in place, it's sure that
   moving to qt is a big task ; even though, thanks to qt's GUI
   designer, it's possible to quickly reproduce the structure of the
   wxwidget application with QT widgets.

   If you want to see the power of Qt, I highly advice you to browse
   the very nice "demos" included in both the Qt and PyQt packages -
   those are Gui applications that let you watch all kind of abilities
   very fastly.
   Also, something that wxwidgets will surely never be able to do :
   
http://labs.trolltech.com/blogs/2008/12/02/widgets-enter-the-third-dimension-wolfenqt/

   The 2 products (and the Gui designer, docs and demos) can be
   downloaded from these pages :
   http://www.qtsoftware.com/products/
   http://www.riverbankcomputing.co.uk/software/pyqt/download

   And if you have some time for reading :
   http://www.qtsoftware.com/files/pdf/qt-4.4-whitepaper
   http://doc.trolltech.com/4.5/index.html

   Good time with all that,
   regards,
   Pascal



   Qijing Li a écrit :

Thank you for sharing this information.

I started to use wxPython two years ago,  which fit my needy very
well because
the jobs I worked on didn't focus on GUI. But now , the project I
am working on
involves much drawing shapes and looking, most of wxPython works
for me,
but one thing, as you mentioned, transparency drove me nuts.

 wxPython suppose transparent window, but not transparent
background that is right what I need. I did research a lot and was
trying to find a proper way to get it, it turns out that I found
two tricky way, one is to use wx.EVT_ERASE_BACKGROUND tricky, the
other is to copy the image of background under the window as the
background image. Although the problem is solved, I feel
uncomfortable  about this.
I hope wxPython supports  real transparency some day.

Recently, I have no plan to transmit to other frameworks, such as
PyQt.
I'm really interested in what is differences between them,  I'll
check it.
Is there demo of PyQt ? or could you give me some links if they
are in the bag.

Have a good day!
Miles







On Tue, May 5, 2009 at 11:42 AM, Pascal Chambon
mailto:chambon.pas...@wanadoo.fr>> wrote:


The fact that Python is a dynamic language offers, in my
opinion, a huge advantage to quickly setup a GUI, without
caring about the infinite details of the variable types and
function signatures.
Its good handling of "function as first-class objects" is also
precious when comes the time of setting callbacks (I can't
bear anymore the way Swing does it, with interfaces etc.)

But much depends on the framework used, too. I've used
wxPython for a multimedia project, and actually it lacked a
lot of necessary features (transparency, event loop tuning,
multithreading support...), but that was 1 year ago, maybe
things have changed.
Anyway, I'd advocate the use of PyQt, which really offers
tremendous possibilities - if your application isn't a simple
office application, its' really worth turning towards pyqt.

Regards,
Pascal



Leon a écrit :

I think there are two advantages over java for GUI application

First, python is more productive and has very rich third modules
support,
you can check the demo of wxPython.

Second, you can develop native-looking GUI

BTW: I'm developing GUI application using python and wxPython.



Second,
On May 4, 11:41 pm, srinivasan srinivas  

wrote:
  

Could you tell me does Python have any advantages over Java for the 
development of GUI applications?

Thanks,
Srini

  Now surf faster and smarter ! Check out the new Firefox 3 - Yahoo! 
Editionhttp://downloads.yahoo.com/in/firefox/?fr=om_email_firefox 



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


  






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


Re: Public attributes with really private data

2009-05-08 Thread Mark Summerfield
[snip]
> By the way, your Attribute descriptor stores the value for all instances of
> A in the same variable...
>
> Peter

You're right.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Public attributes with really private data

2009-05-08 Thread Peter Otten
Mark Summerfield wrote:

> On 8 May, 08:19, Peter Otten <__pete...@web.de> wrote:
>> MarkSummerfieldwrote:
>> > I had a quick search & didn't find anything _nice_ that produced
>> > attributes with really private data, so I came up with a possible
>> > solution---for Python 3.
>>
>> Do really you think what you suggest below is "nice"?
> 
> Well the code isn't ugly and doesn't mess with the call stack etc.
> 
>> By the way, your Attribute descriptor stores the value for all instances
>> of A in the same variable...
> 
> It seems like it does, but it doesn't. The hidden_value is an instance
> variable that is created every time an Attribute object is created.
> 
 from Attribute import *
 class A:
> a = Attribute("a", 5, lambda *a: True)
> b = Attribute("b", 5, lambda *a: True)
 class B:
> a = Attribute("a", 5, lambda *a: True)
> b = Attribute("b", 5, lambda *a: True)
 a = A()
 b = B()
 a.a,a.b,b.a,b.b
> (5, 5, 5, 5)
 a.a=1;a.b=2;b.a=3;b.b=4
 a.a,a.b,b.a,b.b
> (1, 2, 3, 4)

But attribute values are shared between all instances of the same class:

>>> class A:
... x = Attribute("x", 42, lambda *a: True)
...
>>> a = A()
>>> b = A()
>>> a.x, b.x
(42, 42)
>>> a.x = "yadda"
>>> a.x, b.x
('yadda', 'yadda')

Peter

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


Re: Python 3.1 beta 1

2009-05-08 Thread pruebauno
On May 7, 6:33 pm, Benjamin Peterson  wrote:
>   latinmail.com> writes:
>
> > Congratulations!
>
> Thanks!
>
>
>
> > Is it just me or was some nice summary output added to the make
> > process? I get a nice list of modules that didn't compile and the ones
> > where the library could not be found.
>
> Are you compiling on a different platform? The nice output has been around 
> for a
> while, bu only on non-Windows platforms.

Not really, I was on AIX. It is probably just me then, probably
because for the first time I see it making it through the whole
process even with the Tkinter libraries missing.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Public attributes with really private data

2009-05-08 Thread Mark Summerfield
On 8 May, 13:56, Peter Otten <__pete...@web.de> wrote:
> MarkSummerfieldwrote:
> > On 8 May, 08:19, Peter Otten <__pete...@web.de> wrote:
> >> MarkSummerfieldwrote:
> >> > I had a quick search & didn't find anything _nice_ that produced
> >> > attributes with really private data, so I came up with a possible
> >> > solution---for Python 3.
>
> >> Do really you think what you suggest below is "nice"?
>
> > Well the code isn't ugly and doesn't mess with the call stack etc.
>
> >> By the way, your Attribute descriptor stores the value for all instances
> >> of A in the same variable...
>
> > It seems like it does, but it doesn't. The hidden_value is an instance
> > variable that is created every time an Attribute object is created.
>
>  from Attribute import *
>  class A:
> > a = Attribute("a", 5, lambda *a: True)
> > b = Attribute("b", 5, lambda *a: True)
>  class B:
> > a = Attribute("a", 5, lambda *a: True)
> > b = Attribute("b", 5, lambda *a: True)
>  a = A()
>  b = B()
>  a.a,a.b,b.a,b.b
> > (5, 5, 5, 5)
>  a.a=1;a.b=2;b.a=3;b.b=4
>  a.a,a.b,b.a,b.b
> > (1, 2, 3, 4)
>
> But attribute values are shared between all instances of the same class:
>
> >>> class A:
>
> ...     x = Attribute("x", 42, lambda *a: True)
> ...>>> a = A()
> >>> b = A()
> >>> a.x, b.x
> (42, 42)
> >>> a.x = "yadda"
> >>> a.x, b.x
>
> ('yadda', 'yadda')
>
> Peter

Yes. I did think of trying to create the closures dynamically the
first time the getter or setter was called---but that _is_ getting
ugly, so I'll give it up:-)

Thanks!

--
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
C++, Python, Qt, PyQt - training and consultancy
"Programming in Python 3" - ISBN 0137129297
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6, File read() problems in Windows Xp

2009-05-08 Thread pruebauno
On May 8, 5:08 am, Li Wang  wrote:
> Hi  Dave:
> Thank you very much for you explanation:)
>
> > Chances are you forgot the "b" parameter to open().  Unnecessary in Unix, it
> > tells the library to *not* translate \r\n  to \n upon read, or the inverse
> > on write.  In other words, with the "b" parameter, the file is read in
> > unchanged.
>
> So, if I am using python in Linux, do open('file', 'r') and
> open('file', 'rb') work the same way?
>
> Thanks,
>
> Best regards,
> Li

In old Python up to 2.6, YES.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6, File read() problems in Windows Xp

2009-05-08 Thread Scott David Daniels

Li Wang wrote:

So, if I am using python in Linux, do open('file', 'r') and
open('file', 'rb') work the same way?


You get identical results, but you ar lying to the reader of your code.
you should include the 'b' if what you want is bytes (or octets if you
prefer), and not use it if what you expect is "text."   Your code
becomes less confusing by using 'b' properly, even if you see no
particular difference.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Tutorial or example use for python-graph library

2009-05-08 Thread Paul Moore
I have just discovered the python-graph library. I've been interested
in graph algorithms for a long time, so I'd like to give this a try.
But there seems to be very little in the way of examples, or tutorial
documentation available. There's the API documentation, but that's not
really narrative form. And there are some examples in the
distribution, but these seem to be essentially artificial examples,
rather than real-world code (and they don't have much in the way of
documentation!)

Are there any reasonably-sized tutorials, or examples of common real-
world code, using this package? My google-fu wasn't strong enough to
find anything directly :-(

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


Re: Python 2.6, File read() problems in Windows Xp

2009-05-08 Thread Li Wang
2009/5/8 Scott David Daniels :
> Li Wang wrote:
>>
>> So, if I am using python in Linux, do open('file', 'r') and
>> open('file', 'rb') work the same way?
>
> You get identical results, but you ar lying to the reader of your code.
> you should include the 'b' if what you want is bytes (or octets if you
> prefer), and not use it if what you expect is "text."   Your code
> becomes less confusing by using 'b' properly, even if you see no
> particular difference.
>
Thanks a lot, very helpful:D
>



-- 
Li
--
Time is all we have
and you may find one day
you have less than you think
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6, File read() problems in Windows Xp

2009-05-08 Thread Li Wang
2009/5/8  :
> On May 8, 5:08 am, Li Wang  wrote:
>> Hi  Dave:
>> Thank you very much for you explanation:)
>>
>> > Chances are you forgot the "b" parameter to open().  Unnecessary in Unix, 
>> > it
>> > tells the library to *not* translate \r\n  to \n upon read, or the inverse
>> > on write.  In other words, with the "b" parameter, the file is read in
>> > unchanged.
>>
>> So, if I am using python in Linux, do open('file', 'r') and
>> open('file', 'rb') work the same way?
>>
>> Thanks,
>>
>> Best regards,
>> Li
>
> In old Python up to 2.6, YES.
Thank you:D



-- 
Li
--
Time is all we have
and you may find one day
you have less than you think
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tutorial or example use for python-graph library

2009-05-08 Thread (e.g. emre)
On May 8, 3:21 pm, Paul  Moore  wrote:
> I have just discovered the python-graph library. I've been interested
> in graph algorithms for a long time, so I'd like to give this a try.
> But there seems to be very little in the way of examples, or tutorial
> documentation available. There's the API documentation, but that's not
> really narrative form. And there are some examples in the
> distribution, but these seem to be essentially artificial examples,
> rather than real-world code (and they don't have much in the way of
> documentation!)
>
> Are there any reasonably-sized tutorials, or examples of common real-
> world code, using this package? My google-fu wasn't strong enough to
> find anything directly :-(
>
> Thanks,
> Paul

Hi,
you might want to check networkx as well, it is considerably well
documented:
http://networkx.lanl.gov/
Emre
--
http://mail.python.org/mailman/listinfo/python-list


Re: list comprehension question

2009-05-08 Thread J Kenneth King
Terry Reedy  writes:

> J Kenneth King wrote:
>>
>> Keep in mind that nested comprehensions are still available because
>> they do have a use case that justifies their existence.
>
> Nested comprehensions are available because because the syntax makes
> them available by default and making a fiddly exception would be
> contrary to Python's style.  A list comp creates an iterable. A list
> comp requires use of an iterable.  Therefore, a list comp may use a
> list comp.
>
>> However, I
>> think the Python documentation warns against their use because people
>> might rely on them for problems where they aren't necessary and since
>> they are difficult to read... it can lead to difficult to read code.
>
> Whenever the expression that results in the iterable used by a list
> comp is sufficiently complex, readability is improved by pulling it
> out as a separate statement. Nested list comps are often examplex of
> such sufficiently complex expressions, but not the only possible one.
>
> tjr

Agreed. A very succinct explanation of the point I was trying to make.
--
http://mail.python.org/mailman/listinfo/python-list


Re: SQL and CSV

2009-05-08 Thread Nick
On May 8, 1:49 pm, "andrew cooke"  wrote:
> Lawrence D'Oliveiro wrote:
> > In message , Peter Otten wrote:
>
> >> While it may not matter here using placeholders instead of manually
> >> escaping user-provided values is a good habit to get into.
>
> > Until you hit things it can't deal with.
>
> The post you are replying to was talking about using the SQL library's "?"
> syntax that automatically escapes values.  The usual reason this is
> recommended (if I have understood correctly) is that the library code is
> much more likely to foil injection attacks.  I have seen this mentioned
> often and assume it is good advice.
>
> Can you expand on your comment?  I assume you are thinking of how the
> library might handle some strange class.  But aren't the number of types
> limited by SQL?  In which case a "thing that can't be handled" could
> presumably be managed by adding an appropriate __str__ or __float__ or
> whatever?  And you would still use the library to give safety with other
> values.
>
> Maybe you could give an example of the kind of problem you're thinking of?
>
> Thanks,
> Andrew

Injection attacks aren't an issue, its a local app.

It's part of a reconciliation system, where sometimes data is in csv
files. If you want the whole csv file, you can use csv module without
a problem.

In some cases, I need to manipulate the data.

The choices are hard code the manipulation, or load the data from a
config file.

So what I've got is the query in the config and I can process it.

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


Re: Compiling snippets of python code

2009-05-08 Thread Scott David Daniels

Basil Brush wrote:

I need some advice on compiling snippets of python source at runtime. So
perhaps some python experts can point the way.

I am rewriting an old Java app in python. It tries to find solutions to
computational problems based on the idea of genetic evolution. The Java
version just used an array of bytes for the genomes. These byte
sequences were bytecode which told a rudimentary VM (virtual machine)
which maths functions to call. It used another array as a small chunk of
virtual memory for doing the calculations.


Unlike Java and C++, functions and methods are first class.  You can
make lists and dictionaries containing functions, and that would be
the normal Python way of handling this, rather than generating source
from snippets.  You should take a look at Numpy if the "maths functions"
are operating on large chunks of data (fft, matrix operations, and the
like).  If the operations are smallish things, pure Python is likely the
way to go.  I don't understand what the "other array as a small chunk of
virtual memory" might be; my first take is YAGNI.


Having seen the docs on python's compile module, I'm thinking of doing
it differently in the new python version. My aim is to have the genomes
made up of a sequence of python source snippets, with each snippet to be
randomly generated, compiled, and executed at runtime. The advantage of
this is that it gives me greater flexibility and I can change what
actions the genomes can do without having to add new functions to my VM.

But there's some crucial points. When the snippet is executed I would
need to pass in a list or array, and I need the list back again with any
changes that were made; this is the virtual memory and how I would get
the results back, and is also how the snippet would get data from a
previous snippet in a sequence. 



Here is a toy-like version of what you might want to do:
# Some operations:
def double(vec):
return [x * 2 for x in vec]

def alternate(vec):
'''An "unshuffling" step'''
return vec[::2] + vec[1::2]

def halve(vec):
return [x / 2 for x in vec]

# Some execution lists:
processing = [double, alternate, halve, alternate]
new_processing = alternate(processing) # you can shuffle any list

assert new_processing == [double, halve, alternate, alternate]

def perform(processes, data):
for step in processes:
data = step(data)
return data

start = [x * x for x in range(10)]
assert perform(processing, start) == perform(new_processing, start)
print start
mid = perform(processing, start)
print mid
print perform(processing, mid)
print perform(processing * 2, start)

prints:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 16, 64, 9, 49, 4, 36, 1, 25, 81]
[0, 49, 25, 9, 1, 64, 36, 16, 4, 81]
[0, 49, 25, 9, 1, 64, 36, 16, 4, 81]


How would I do this? Also, there is a

database of input data. Rather than pass all that data to the snippet
I'd rather have functions in my module which the snippet could call to
get data. So what's the scope of an executing piece of code? Can it
access my modules and functions?

First, let go of managing the data allocation.  Second, realize passing
a list or array is simple and cheap, and _not_ proportional to the size
of the list or array.  You are passing the actual object.  You really
need to run through the tutorial; these questions will be answered there.
Sit down with the tutorial and the interpretter, executing anything you
don't quite understand.  I did it in IDLE, but you may prefer straight
command line.


My linux system has python 2.5 and I noticed that the docs say the
compile module has been removed from python 3.0. So I'm concerned about
whether my app would work in 3.0 if I upgraded. Does anyone know if they
moved the compiler to another module or simply removed it entirely?

Although I don't think you should be working with the compiler, if
you want to use something like that, you'd be better advised to use
the "ast" module first added in 2.6.  But for now, don't borrow trouble
you don't need. Rethink your problem and write it in Python.  Don't try
to do a line-by-line translation, you'll just have a slow awkward Python
program with a Java heart.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Creating temperory files for a web application

2009-05-08 Thread Stephen Hansen
>
>
> Thank you Diez.
> I would like to go ahead with the cleanest solution indeed.
> I am creating the image on the fly. But I could not understand what
> you meant by render to memory as a string.
> How do we send the image to the browser?
>
> Were you mentioning about having the image as a string and then
> passing to the browser based on data URL scheme  ?
> Or is it something else like XBM format or something? I am sorry - but
> I am quite unsure of what you meant?
>
> I am actually creating PDFs, CSVs and images on the fly. So, I need to
> delete them all after that.
> The images can be somewhat large - ~2MB. The RFC mentions that large
> data cannot be sent that way.
>

The question is, how are you generating these images? What you consider a
"file" and what a web server considers a "file" is really meaningless
actually. To a web browser, all a "file" is is a stream of content with a
certain content-type which it uses to determine how to treat it. This isn't
about the RFC2397. The web browser has no idea if the content its fetching
is from a file or a database or generated on the fly-- its all the same
thing. There's a URL which returns data, when requested. That data might be
a HTML file (as determined by its Content-type), in which case the browser
renders it. Or it might be a JPG, in which case it displays it. Or it might
be a zip file in which case it probably asks you where you want to save it.

Depending on how exactly you're actually "generating" the image, its quite
possible you don't need to use a real file at all. You can use a file-like
object, such as (c)StringIO and pass it to your image generation routines
which will generate the entire image in memory. You can write to this
file-like object as if it were a real file on the disk somewhere, seek,
scan, pass it to most libraries that need file objects and then when
done, you can return its contents... all without a -real- file on disk ever
being touched.

Like so vaguely:
f = cStringIO.StringIO()
my_library_which_makes_images(f)
f.seek(0)
return f.read()

Exactly how you indicate what the Content-type will be and do that will
depend on what web framework you're using.

For example, on one app I have -- I'm using TurboGears -- I do something
like this:

@expose(format="image/jpeg", content_type="image/jpeg")
def getJPEG(self, element_number):
element = self._resourceManager.getElement(element_number)
if element:
return element.data

return ''

Now the specifics of what's going on aren't important. But I'm connecting to
a remote system, and getting an object which contains the entire contents of
a JPEG in a single string. So the entire file is in memory. I could then
tweak or manipulate it with PIL to change that file all without any
filesystem access, working entirely on file-like objects in memory, then
return the contents.

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


Re: Public attributes with really private data

2009-05-08 Thread Mark Summerfield
On 8 May, 13:56, Peter Otten <__pete...@web.de> wrote:
> Mark Summerfield wrote:
> > On 8 May, 08:19, Peter Otten <__pete...@web.de> wrote:
> >> MarkSummerfieldwrote:
> >> > I had a quick search & didn't find anything _nice_ that produced
> >> > attributes with really private data, so I came up with a possible
> >> > solution---for Python 3.
>
> >> Do really you think what you suggest below is "nice"?
>
> > Well the code isn't ugly and doesn't mess with the call stack etc.
>
> >> By the way, your Attribute descriptor stores the value for all instances
> >> of A in the same variable...
>
> > It seems like it does, but it doesn't. The hidden_value is an instance
> > variable that is created every time an Attribute object is created.
>
>  from Attribute import *
>  class A:
> > a = Attribute("a", 5, lambda *a: True)
> > b = Attribute("b", 5, lambda *a: True)
>  class B:
> > a = Attribute("a", 5, lambda *a: True)
> > b = Attribute("b", 5, lambda *a: True)
>  a = A()
>  b = B()
>  a.a,a.b,b.a,b.b
> > (5, 5, 5, 5)
>  a.a=1;a.b=2;b.a=3;b.b=4
>  a.a,a.b,b.a,b.b
> > (1, 2, 3, 4)
>
> But attribute values are shared between all instances of the same class:
>
> >>> class A:
>
> ...     x = Attribute("x", 42, lambda *a: True)
> ...>>> a = A()
> >>> b = A()
> >>> a.x, b.x
> (42, 42)
> >>> a.x = "yadda"
> >>> a.x, b.x
>
> ('yadda', 'yadda')
>
> Peter

OK, I couldn't quite give it up. But the solution isn't nice or good.
It does work, but at the cost of an extra dictionary lookup on every
get or set, plus a dictionary to hold all the getters & setters. I
_don't recommend it_, but here it is anyway. I've done with it now:-)

class Attribute:

__accessors = {}

def __init__(self, name, first_value=None, validator=None):
self.name = name
self.first_value = first_value
self.validator = validator

def __get__(self, instance, owner=None):
if instance is None:
return self
if (id(instance), self.name) not in self.__accessors:
self.__makeAccessors(instance)
return self.__accessors[id(instance), self.name][0](instance)


def __set__(self, instance, value):
if (id(instance), self.name) not in self.__accessors:
self.__makeAccessors(instance)
setter = self.__accessors[id(instance), self.name][1]
if setter is None:
raise AttributeError("'{0}' is read-only".format(
 self.__name__))
return setter(instance, value)


def __makeAccessors(self, instance):
hidden_value = self.first_value
getter = lambda self: hidden_value
if self.validator is not None:
def set(instance, value):
if self.validator(instance, value):
nonlocal hidden_value
hidden_value = value
else:
raise ValueError("'{0}' is not valid for {1}"
 .format(value, name))
setter = set
else:
setter = None
self.__accessors[id(instance), self.name] = (getter, setter)

--
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
C++, Python, Qt, PyQt - training and consultancy
"Programming in Python 3" - ISBN 0137129297
--
http://mail.python.org/mailman/listinfo/python-list


unicode bit me

2009-05-08 Thread anuraguni...@yahoo.com
#how can I print a list of object which may return unicode
representation?
# -*- coding: utf-8 -*-

class A(object):

def __unicode__(self):
return u"©au"

__str__ = __repr__ = __unicode__

a = A()

try:
print a # doesn't work?
except UnicodeEncodeError,e:
print e
try:
print unicode(a) # works, ok fine, great
except UnicodeEncodeError,e:
print e
try:
print unicode([a]) # what doesn't work?
except UnicodeEncodeError,e:
print e
"""
Now how can I print a list of object which may return unicode
representation?
loop/map is not an option as it goes much deepr in my real code
any can anyoen explain what is happening here under the hood?
"""
--
http://mail.python.org/mailman/listinfo/python-list


Re: Call a function when a thread exits

2009-05-08 Thread Giampaolo Rodola'
On 8 Mag, 03:33, Carl Banks  wrote:
> On May 7, 6:12 pm, "Giampaolo Rodola'"  wrote:
>
>
>
>
>
> > Hi,
> > I'm searching for a smooth way to call a certain function when a
> > thread has finished its job.
> > I guess I can keep calling isAlive() in a loop and call my function
> > when it returns False but it's not very elegant.
> > Actually I'm a bit surprised it doesn't exists an "atexit" function.
> > Something like:
>
> > import threading, time
>
> > def myfun():
> >     time.sleep(1)
> >     print "hello"
>
> > def cleanup():
> >     print "thread finished, starting cleanup operations..."
>
> > t = threading.Thread(target=myfun)
> > t.atexit(target=cleanup)
> > t.start()
>
> > Is there a reason why there's no such thing in the threading module?
>
> You can define your target function to clean up on exit.  Using your
> definitions of myfun and cleanup,
>
> def mycleanfun():
>     try:
>         myfun()
>     finally:
>         cleanup()
>
> t = threading.Thread(target=mycleanfun)
> t.start()
>
> Carl Banks

Yes, I know. I was wondering if it could be a good idea proposing
something like an atexit() function to be included in threading
module.


--- Giampaolo
http://code.google.com/p/pyftpdlib
http://code.google.com/p/psutil
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tutorial or example use for python-graph library

2009-05-08 Thread Scott David Daniels

Paul Moore wrote:

I have just discovered the python-graph library. I've been interested
in graph algorithms for a long time, so I'd like to give this a try.
But there seems to be very little in the way of examples, or tutorial
documentation available. There's the API documentation, but that's not
really narrative form. And there are some examples in the
distribution, but these seem to be essentially artificial examples,
rather than real-world code (and they don't have much in the way of
documentation!)

Are there any reasonably-sized tutorials, or examples of common real-
world code, using this package? My google-fu wasn't strong enough to
find anything directly :-(


Try writing one yourself, as you are learning the interface.  The
package authors will love it, and will probably be overjoyed to
help you as you stumble.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newcomer to Python tutorial question

2009-05-08 Thread Peter Pearson
On Fri, 8 May 2009 10:16:55 +0100, Alan Cameron  wrote:
[snip]
>
> In particular reference to the tutorial section
> http://docs.python.org/3.0/tutorial/datastructures.html#nested-list-comprehensions
>
> There is a word which is ambiguous, at least to me.
>
> Perhaps you can explain the use of the word 'comprehensions'.
>
> Comprehension I understand
> Comprehensions I don't.
>
> Is there a glossary of terms somewhere?

"Comprehension", in this context, is a computer-science term, described
in section 5.1.3 of the web page you quoted.  If you look up
"comprehension" in Wikipedia, you'll get a description of various
uses of the term, including a pointer to:
http://en.wikipedia.org/wiki/List_comprehension

-- 
To email me, substitute nowhere->spamcop, invalid->net.
--
http://mail.python.org/mailman/listinfo/python-list


Re: php to python code converter

2009-05-08 Thread Pascal Chambon

Hello

That's funny, I was precisely thinking about a php to python converter, 
some weeks ago.
Such a tool, allowing for example to convert some CMS like Drupal to 
python, would be a killer app, when we consider the amount of php code 
available.


But of course, there are lots of issues that'd have to be fixed :
- translating the php syntax to python syntax
- forcing scope limitations where php doesn't have any
- handling differences in semantics (for example, the booleanness of "0" 
or)

- handling the automatic variable creation and coertion that php features
- handling the php types like arrays (which are neither python lists nor 
python dicts)
- providing a whole mirror of the php stdlib (string and file functions, 
access to environment vars...)


Some things, like PECL modules, would imo be almost impossible to handle 
(there are already so much trouble to make Cpython extensions available 
to other python implementations...), but I guess that 95% of existing 
php websites could be wholly translated "just" with a language 
translator and an incomplete stddlib replacement.


That's hell a lot of work anyway, so it'd be worth weighing it ^^

Actually, your module "phppython" might already be rather useful, 
because I've crossed here and there people desperately asking for help 
when translating some php function of their own to python.


But if the project were to become bigger, I guess some choices would 
have to be rechecked. For example it seems you parse the php code your 
own way, instead of using existing php parsers ; I think the most 
flexible way would be walking some kind of php abstract syntax tree, and 
translating it to python AST on the way. Also, writting the comments in 
english woudl be mandatory :p


I'd like to have the opinion of people around : do you think that 
complete language translators like php<->python or ruby<->python are 
possible ? Impossible ? Not worth the effort ? Or must be reached by 
another way (eg. Parrot and stuffs) ?


Regards,
Pascal

PS : Am I the only one having most of answers rejected by the antispam 
system of python-list ? That's humiliating :p


bvidinli a écrit :

if anybody needs:
http://code.google.com/p/phppython/
--
http://mail.python.org/mailman/listinfo/python-list


  


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


Path difficulties with Python 2.5 running on Cygwin

2009-05-08 Thread walterbyrd
It workerd fine yesterday, but it won't work today.

I can still run python, but when I try to import csv, I get an error:

File "/usr/lib/python2.5/csv.py", line 8 in   . . .

The module is there. I am guessing that python can not find it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Path difficulties with Python 2.5 running on Cygwin

2009-05-08 Thread walterbyrd
On May 8, 9:22 am, walterbyrd  wrote:
> It workerd fine yesterday, but it won't work today.
>
> I can still run python, but when I try to import csv, I get an error:
>
> File "/usr/lib/python2.5/csv.py", line 8 in   . . .
>
> The module is there. I am guessing that python can not find it.

I should have added:

When I am in /cygdrive/c/Documents and Settings, everything works
fine. But, when I am in /cygdrive/c/Documents and Settings/wbyrd, it
no longer works.

I also get the error: Attribute error: module has no attribute
'reader'

I accidently named a script csv.py, put I deleted that. It seems like
I might need to clear out the python interprator, but I don't know how
to do that.


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


Decorating methods - where do my arguments go?

2009-05-08 Thread Mikael Olofsson

Hi all!

I have long tried to avoid decorators, but now I find myself in a 
situation where I think they can help. I seem to be able to decorate 
functions, but I fail miserably when trying to decorate methods. The 
information I have been able to find on-line focuses on decorating 
functions, and do not mention any special problem regarding methods.


Consider the following example. I start by defining a simple decorator:

>>> class test_decorator(object):
... def __init__(self,func):
... self._func = func
... def __call__(self, *args):
... print 'Decorator:', args
... self._func(*args)

Then I decorate a function:

>>> @test_decorator
... def func(*args):
... print 'Function: ', args

Let's try that:

>>> func(1,2,3)
Decorator: (1, 2, 3)
Function:  (1, 2, 3)

OK! That was what I expected. Let's decorate a method:

>>> class cls(object):
... @test_decorator
... def meth(self,*args):
... print 'Method:   ', args

Then try that:

>>> cls().meth(1,2,3)
Decorator: (1, 2, 3)
Method:(2, 3)

Oops! That's weird. I had expected - or at least wanted - the same 
result as for the function above.


Where did the first argument go? If it was sent to the original method 
meth as the real first argument (self), then why did I not get an exception?


More importantly: How do I write a decorator that does not drop arguments?

I guess it all has to do with the fact that the returned callable isn't 
a method of cls. Is it possible to write a decorator that returns a 
callable that is a method of cls, when used on methods in cls?


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


Re: Path difficulties with Python 2.5 running on Cygwin

2009-05-08 Thread Jerry Hill
On Fri, May 8, 2009 at 11:29 AM, walterbyrd  wrote:
> I accidently named a script csv.py, put I deleted that.

You probably still have a stale csv.pyc in that directory.  Delete that too.

To tell for sure, open the python interpreter and do:
import csv
print csv.__file__

That will tell you exactly where the csv module is being loaded from.

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


Re: php to python code converter

2009-05-08 Thread D'Arcy J.M. Cain
On Fri, 08 May 2009 17:19:13 +0200
Pascal Chambon  wrote:
> That's funny, I was precisely thinking about a php to python converter, 
> some weeks ago.
> Such a tool, allowing for example to convert some CMS like Drupal to 
> python, would be a killer app, when we consider the amount of php code 
> available.

I'm not a big fan of PHP but I don't understand the desireability of
such a tool.  If you have a good PHP app just run it.  The point of
Python in my mind is that it is a cleaner syntax and promotes better
code.  Anything that converts PHP to Python is going to leave you with
some butt-ugly Python.  It also risks adding new bugs.

If you want a Python version of Drupal then perhaps that is the project
that you want to start.  Start fresh using the existing project as your
requirements specification.  Don't automatically import all their
coding choices that may be partially based on the language used.

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: unicode bit me

2009-05-08 Thread Scott David Daniels

anuraguni...@yahoo.com wrote:

#how can I print a list of object which may return unicode
representation?
# -*- coding: utf-8 -*-

class A(object):

def __unicode__(self):
return u"©au"

__str__ = __repr__ = __unicode__

a = A()

try:
print a # doesn't work?
except UnicodeEncodeError,e:
print e
try:
print unicode(a) # works, ok fine, great
except UnicodeEncodeError,e:
print e
try:
print unicode([a]) # what doesn't work?
except UnicodeEncodeError,e:
print e
"""
Now how can I print a list of object which may return unicode
representation?
loop/map is not an option as it goes much deepr in my real code
any can anyoen explain what is happening here under the hood?
"""


It would be a bit easier if people would bother to mention
their Python version, as we regularly get questions from people
running 2.3, 2.4, 2.5, 2.6, 2.7a, 3.0, and 3.1b.  They run computers
with differing operating systems and versions such as: Windows 2000,
OS/X Leopard, ubuntu Hardy Heron, SuSE, 

You might shocked to learn that a good answer often depends on the
particular situation above.  Even though it is easy to say, for example:
platform.platform()  returns  'Windows-XP-5.1.2600-SP3'
sys.version is
'2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)]'


What is happening is that print is writing to sys.stdout, and
apparently that doesn't know how to send unicode to that destination.
If you are running under IDLE, print goes to the output window, and
if you are running from the command line, it is going elsewhere.
the encoding that is being used for output is sys.stdout.encoding.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Path difficulties with Python 2.5 running on Cygwin

2009-05-08 Thread walterbyrd
On May 8, 9:36 am, Jerry Hill  wrote:
> On Fri, May 8, 2009 at 11:29 AM, walterbyrd  wrote:
> > I accidently named a script csv.py, put I deleted that.
>
> You probably still have a stale csv.pyc in that directory.  Delete that too.
>

I don't, I am very certain of that. I have also used find to make
certain there are no other stray versions of csv.py.

> To tell for sure, open the python interpreter and do:
> import csv
> print csv.__file__
>
> That will tell you exactly where the csv module is being loaded from.

Problem is, python will not load the csv module, since it detects an
error. And since I can not load the module, csv.__file__ will not
work.


This file will work:
-
#!/usr/bin/env python

# import csv

print "hello"
--


This file will not work:
-
#!/usr/bin/env python

import csv

print "hello"
--


In later case, I get that error about 'module' object has no attribute
'reader'
--
http://mail.python.org/mailman/listinfo/python-list


Re: free chart lib for Python?

2009-05-08 Thread Glenn Hutchings
On Fri, 08 May 2009 10:27:08 +0800, oyster wrote:

> I mean chart, not plot. If you don't know the difference, you can
> check www.advsofteng.com, which is a commercial program
> 
> is there such a thing with many kinds of chart, i.e. pie-chart,
> line-chart, ..?

You could try matplotlib: http://matplotlib.sourceforge.net.  That can do
all kinds of wizzo plotty/charty stuff.
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess.Popen howto?

2009-05-08 Thread norseman


Øystein ;
Down below: change >yourPy.py  to | yourPy.py
I just noticed the typo.

Sorry

Steve

norseman wrote:

Øystein Johansen (OJOHANS) wrote:

Hi,
 
I have problems understanding the subprocess.Popen object. I have a 
iterative calculation in a process running and I want to pipe the 
output (stdout) from this calculation to a Python script.
 
Let me include a simple code that simulates the calculating process:

/* This code simulates a big iterative calculation */
#include 
#include 
 
int main()

{
 float val[2] = { M_PI, M_E };
 int i;
 
 for ( i = 0; i < 2 i++) {

  sleep( 15 );   /* It's a hard calculation. It take 15 seconds */
  printf("Value: %5.6f\n", val[i] );
  fflush( stdout );
 }
 return 0;
}
 
let's compile this to mycalc: gcc -o mycalc calc.c ... (untested code)
 
In C I have this code which starts the mycalc process and handles the 
output from it:
 
#include 

#include 
#define BUF_SIZE 256
 
int main()

{
 FILE *pip;
 char line[BUF_SIZE];
 
 pip = popen("mycalc", "r");

 assert( pip != NULL );
 
 while ( fgets( line, BUF_SIZE, pip )) {

  printf( "Hello; I got: %s \n", line );
  fflush( stdout );
 }
 pclose( pip );
 return 0;
}
How can I make such while-loop in Python? I assume I should use 
subprocess.Popen(), but I can't figure out how?
 
-Øystein
 
 


---
The information contained in this message may be CONFIDENTIAL and is
intended for the addressee only. Any unauthorised use, dissemination 
of the

information or copying of this message is prohibited. If you are not the
addressee, please notify the sender immediately by return e-mail and 
delete

this message.
Thank you.




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



If you don't like a lot of typing that obscures the process,
take a look at os.Popen2  Pg.39 or so in Lib.pdf for 2.5.2
In this case - the popen3 is probably your best bet.

I took a test run on "subprocess" a few months ago. My review:
excessive typing to accomplish the simple.  BlackBox stuff is supposed 
to be short and sweet.


BlackBox was the term applied to drivers and couplers back when.
Back when: one started by writing a subroutine that got used.
   next one got to write a program
   next one got to write an application
   then a BlackBox
   from there one could graduate to OS
That was back when!


to repeat from another of my postings:
---
processPython 2.5.2 (r252:60911, Mar  4 2008, 10:40:55)
[GCC 3.3.6] on linux2
Type "help", "copyright", "credits" or "license" for more information.

 >>> import os
 >>> AbWd = os.spawnlp( os.P_WAIT,"abiword","abiword","")

The P_WAIT stops python until the program (abiword in this case) 
completes.  The "" at the end are for tokens to be given to the program 
and yes - contrary to manual, the program MUST be there TWICE (complete 
with any path needed).


for windows this works:
(for cut and paste from cmd.exe, see:
  Re: Copy & Paste in a Dos box  from norseman  05/06/2009 4:28PM
)

Python 2.5.1 ... on win32
 >>> import os
 >>> result = os.spawnl( os.P_WAIT, "d:\\winmcad\\mcad","")

Runs the program mcad. Returns to python when mcad exits.
---


In your case:  substitute ..."your_compiled_c_program", " >yourPy.py")
at the obvious places.

In case this isn't clear;
  method 1:  py1.py starts compiled.c which redirects to yourPy.py
  method 2:  py1.py uses os.popen3(compiled.c...) & the two work it out.
In either case the receiver at the end stays open until completion so 
sleep() things are not needed.  (may need to test for EOL and EOT)


HTH

Steve
norse...@hughes.net
--
http://mail.python.org/mailman/listinfo/python-list



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


Re: Path difficulties with Python 2.5 running on Cygwin

2009-05-08 Thread walterbyrd
On May 8, 10:01 am, walterbyrd  wrote:
> On May 8, 9:36 am, Jerry Hill  wrote:
>
> > On Fri, May 8, 2009 at 11:29 AM, walterbyrd  wrote:
> > > I accidently named a script csv.py, put I deleted that.
>
> > You probably still have a stale csv.pyc in that directory.  Delete that too.
>

Okay, I got it. I was looking for csv.py - because that is what I
accidently created. I don't know where csv.pyc came from, unless
python renamed it that when it tried to load csv.py, or something.

In any case, it seems to work now. Thanks again for your help.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Compiling snippets of python code

2009-05-08 Thread Basil Brush
Scott David Daniels wrote:

> make lists and dictionaries containing functions, and that would be
> the normal Python way of handling this, rather than generating source
> from snippets.  You should take a look at Numpy if the "maths functions"

Thank you very much for your response. I hadn't thought of doing it that
way and I feel that would be the best way, especially as a list of maths
functions would make the code for genome recombination and mutation
simpler to rewrite.


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


Re: php to python code converter

2009-05-08 Thread Pascal Chambon

D'Arcy J.M. Cain a écrit :

On Fri, 08 May 2009 17:19:13 +0200
Pascal Chambon  wrote:
  
That's funny, I was precisely thinking about a php to python converter, 
some weeks ago.
Such a tool, allowing for example to convert some CMS like Drupal to 
python, would be a killer app, when we consider the amount of php code 
available.



I'm not a big fan of PHP but I don't understand the desireability of
such a tool.  If you have a good PHP app just run it.  The point of
Python in my mind is that it is a cleaner syntax and promotes better
code.  Anything that converts PHP to Python is going to leave you with
some butt-ugly Python.  It also risks adding new bugs.

If you want a Python version of Drupal then perhaps that is the project
that you want to start.  Start fresh using the existing project as your
requirements specification.  Don't automatically import all their
coding choices that may be partially based on the language used.

  
I agree that, in any way, the code resulting from this translation would 
be anything but pythonic :p


The point would rather be to consider code translated from php, ruby, 
perl or anything as extension modules, which have to be wrapped with 
pythonic interfaces (much like c/c++ libraries actually), or which are 
supposed to be deeply refactored.
It's always a pity when libraries available in a language have to be 
reproduced in another - even though building the translation tools would 
maybe ask for too much effort.


Concerning applications, like Drupal, it'd be different of course - I 
have no precise plan on how Drupal could be translated and then made 
"maintainable" in python, but for sure Python lacks a similar CMS, 
easier to approach than Plone and much more feature-full than others 
(Slemetonz, Pylucid...). And I don't feel quite ready for implementing 
such a thing myself ^^


Maybe the translation approach isn't the right one ; surely the best 
would be an interoperability at a lower level, like we have in Jpype, 
the DLR of .Net, Parrot, ironclad etc... but even with those projects, 
we're far from a fluent interoperability between languages, which would 
allow you to pick the best modules in the languages that fit the most 
for each of your tasks, on the platform you want  (I guess that's just a 
geeky dream).


Regards,
pascal


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


Re: php to python code converter

2009-05-08 Thread Pascal Chambon


D'Arcy J.M. Cain a écrit :

On Fri, 08 May 2009 17:19:13 +0200
Pascal Chambon  wrote:
  
That's funny, I was precisely thinking about a php to python converter, 
some weeks ago.
Such a tool, allowing for example to convert some CMS like Drupal to 
python, would be a killer app, when we consider the amount of php code 
available.



I'm not a big fan of PHP but I don't understand the desireability of
such a tool.  If you have a good PHP app just run it.  The point of
Python in my mind is that it is a cleaner syntax and promotes better
code.  Anything that converts PHP to Python is going to leave you with
some butt-ugly Python.  It also risks adding new bugs.

If you want a Python version of Drupal then perhaps that is the project
that you want to start.  Start fresh using the existing project as your
requirements specification.  Don't automatically import all their
coding choices that may be partially based on the language used.

  
I agree that, in any way, the code resulting from this translation would 
be anything but pythonic :p


The point would rather be to consider code translated from php, ruby, 
perl or anything as extension modules, which have to be wrapped with 
pythonic interfaces (much like c/c++ libraries actually), or which are 
supposed to be deeply refactored.
It's always a pity when libraries available in a language have to be 
reproduced in another - even though building the translation tools would 
maybe ask for too much effort.


Concerning applications, like Drupal, it'd be different of course - I 
have no precise plan on how Drupal could be translated and then made 
"maintainable" in python, but for sure Python lacks a similar CMS, 
easier to approach than Plone and much more feature-full than others 
(Slemetonz, Pylucid...). And I don't feel quite ready for implementing 
such a thing myself ^^


Maybe the translation approach isn't the right one ; surely the best 
would be an interoperability at a lower level, like we have in Jpype, 
the DLR of .Net, Parrot, ironclad etc... but even with those projects, 
we're far from a fluent interoperability between languages, which would 
allow you to pick the best modules in the languages that fit the most 
for each of your tasks, on the platform you want  (I guess that's just a 
geeky dream).


Regards,
pascal


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


Re: free chart lib for Python?

2009-05-08 Thread cgoldberg
> You could try matplotlib:http://matplotlib.sourceforge.net.

+1 Matplotlib.
It's a very nice module with impressive graphing/charting/plotting
capabilities.
--
http://mail.python.org/mailman/listinfo/python-list


Re: SQL and CSV

2009-05-08 Thread andrew cooke

even if you're not open to injection attacks, you're still less likely to
get escaping correct than a puprose written, widely used library.

my request for more information was directed to lawrence, who said "until
you hit things it can't deal with" which seemed to be some kind of cryptic
argument against parameters.

andrew


Nick wrote:
> On May 8, 1:49 pm, "andrew cooke"  wrote:
>> Lawrence D'Oliveiro wrote:
>> > In message , Peter Otten wrote:
>>
>> >> While it may not matter here using placeholders instead of manually
>> >> escaping user-provided values is a good habit to get into.
>>
>> > Until you hit things it can't deal with.
>>
>> The post you are replying to was talking about using the SQL library's
>> "?"
>> syntax that automatically escapes values.  The usual reason this is
>> recommended (if I have understood correctly) is that the library code is
>> much more likely to foil injection attacks.  I have seen this mentioned
>> often and assume it is good advice.
>>
>> Can you expand on your comment?  I assume you are thinking of how the
>> library might handle some strange class.  But aren't the number of types
>> limited by SQL?  In which case a "thing that can't be handled" could
>> presumably be managed by adding an appropriate __str__ or __float__ or
>> whatever?  And you would still use the library to give safety with other
>> values.
>>
>> Maybe you could give an example of the kind of problem you're thinking
>> of?
>>
>> Thanks,
>> Andrew
>
> Injection attacks aren't an issue, its a local app.
>
> It's part of a reconciliation system, where sometimes data is in csv
> files. If you want the whole csv file, you can use csv module without
> a problem.
>
> In some cases, I need to manipulate the data.
>
> The choices are hard code the manipulation, or load the data from a
> config file.
>
> So what I've got is the query in the config and I can process it.
>
> Nick
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>


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


Re: Path difficulties with Python 2.5 running on Cygwin

2009-05-08 Thread Scott David Daniels

walterbyrd wrote:

On May 8, 10:01 am, walterbyrd  wrote:

On May 8, 9:36 am, Jerry Hill  wrote:


On Fri, May 8, 2009 at 11:29 AM, walterbyrd  wrote:

I accidently named a script csv.py, put I deleted that.

You probably still have a stale csv.pyc in that directory.  Delete that too.

Okay, I got it. I was looking for csv.py - because that is what I
accidently created. I don't know where csv.pyc came from, unless
python renamed it that when it tried to load csv.py, or something.


You _need_ to understand where csv.pyc came from, or you will hit
this problem frequently.

When you import any module in python, the python interpreter looks
for a "compiled" version of that mdule -- a .pyc (or when optimizing
.pyo) file.  If it finds it, it checks that it was compiled from the
corresponding .py (or .pyw) file.  If no .pyc is found, or if the
.pyc that was found doesn't match the corresponding .py file, the
.py (or .pyw) file is "compiled into either a .pyc or .pyo, and the
contents of that .pyc or .pyo are used to build the module.

So, importing a module will write a .pyc or .pyo file unless an
appropriate .pyc or .pyo file is found.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Decorating methods - where do my arguments go?

2009-05-08 Thread Peter Otten
Mikael Olofsson wrote:

> Hi all!
> 
> I have long tried to avoid decorators, but now I find myself in a
> situation where I think they can help. I seem to be able to decorate
> functions, but I fail miserably when trying to decorate methods. The
> information I have been able to find on-line focuses on decorating
> functions, and do not mention any special problem regarding methods.
> 
> Consider the following example. I start by defining a simple decorator:
> 
>  >>> class test_decorator(object):
> ... def __init__(self,func):
> ... self._func = func
> ... def __call__(self, *args):
> ... print 'Decorator:', args
> ... self._func(*args)
> 
> Then I decorate a function:
> 
>  >>> @test_decorator
> ... def func(*args):
> ... print 'Function: ', args
> 
> Let's try that:
> 
>  >>> func(1,2,3)
> Decorator: (1, 2, 3)
> Function:  (1, 2, 3)
> 
> OK! That was what I expected. Let's decorate a method:
> 
>  >>> class cls(object):
> ... @test_decorator
> ... def meth(self,*args):
> ... print 'Method:   ', args
> 
> Then try that:
> 
>  >>> cls().meth(1,2,3)
> Decorator: (1, 2, 3)
> Method:(2, 3)
> 
> Oops! That's weird. I had expected - or at least wanted - the same
> result as for the function above.
> 
> Where did the first argument go? If it was sent to the original method
> meth as the real first argument (self), then why did I not get an
> exception?
> 
> More importantly: How do I write a decorator that does not drop arguments?
> 
> I guess it all has to do with the fact that the returned callable isn't
> a method of cls. Is it possible to write a decorator that returns a
> callable that is a method of cls, when used on methods in cls?
> 
> /MiO

You have to turn your decorator into a descriptor by providing a __get__() 
method. A primitive example:

class test_decorator(object):
def __init__(self,func):
self._func = func
def __call__(self, *args):
print 'Decorator:', args
self._func(self.inst, *args)
def __get__(self, inst, cls):
self.inst = inst
return self

Read more about the details at

http://users.rcn.com/python/download/Descriptor.htm

Peter

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


Re: php to python code converter

2009-05-08 Thread Dotan Cohen
> I'm not a big fan of PHP but I don't understand the desireability of
> such a tool.  If you have a good PHP app just run it.  The point of
> Python in my mind is that it is a cleaner syntax and promotes better
> code.  Anything that converts PHP to Python is going to leave you with
> some butt-ugly Python.  It also risks adding new bugs.
>
> If you want a Python version of Drupal then perhaps that is the project
> that you want to start.  Start fresh using the existing project as your
> requirements specification.  Don't automatically import all their
> coding choices that may be partially based on the language used.
>

It would be a great learning tool. I am pretty decent with PHP but
just getting started in Python. This might help such users flatten out
the learning curve.

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
--
http://mail.python.org/mailman/listinfo/python-list


building 32-bit PyQT4 and matplotlib on X86_64

2009-05-08 Thread enricong
I'm having some issues attempting to build PyQT4 and matplotlib.  I'm
on a 64-bit machine and am trying to build a 32-bit version.  I have
already installed seperate 32-bit libs and a 32-bit version of python
however I continue to run into two basic problems

With PyQT4, I dont know how to tell it that I want to compile 32bit.
I run into a problem at the very beginning when it runts qtdirs.mk and
there -m32 isnt there.  I tried adding it in and manually running
make, but then I have the second problem

with matplotlib and PyQT4, eventhough the "-m32" flag is being used
with g++ and /usr/lib is included in the library search path, I run
into problems where I get a message saying something like:

/usr/bin/ld: skipping incompatible /usr/lib64/libz.so when searching
for -lz
then
/usr/bin/ld: cannot find -lz

I had this exact problem with a few modules while trying to build
Python 32 bit, however I was able to substitude -lz with the full path
to the library /usr/lib/libz.so.1

This would be impractical to do with matplotlib.
This is also just one example, I have problems with other libraries
too.


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


How to debug this import problem?

2009-05-08 Thread Iwan Vosloo
Hi there,

We have a rather complicated program which does a bit of os.chdir and
sys.path manipulations.  In between all of this, it imports the decimal
module several times.

However, it imports a new instance of decimal sometimes.  (Which is a
problem, since a decimal.Decimal (imported at point A) now is not the
same as that imported somewhere else.

In trying to figure out what's happening, we've changed the code in
decimal to print out id(sys) when decimal gets imported.  This also
gives back different values at different times.  My suspicion is that
when importing python tries to check sys.modules - but each time sys is
a different sys already.

Any ideas of how we can gather more data to find out exactly what causes
this? The path manipulations is a suspect, but unfortunately we cannot
remove it.  If we can trace the problem from the import end though, we
may be able to isolate the exact one which is the problem.

This code incidentally also runs in a virtualenv environment AND uses
setuptools.  None of these complications can be removed...

Regards
- Iwan

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


Re: How do I test the integrity of a Python installation in Debian and Ubuntu

2009-05-08 Thread Aahz
In article ,
Geoff Gardiner   wrote:
>
>How do I assure myself of the integrity of a Python installation
>acquired using apt-get install on Debian and Ubuntu?

How important is the apt-get requirement?  Building Python yourself in
this situation sounds like it would be simpler/safer.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
--
http://mail.python.org/mailman/listinfo/python-list


import overwrites __name__

2009-05-08 Thread Marco
Hi,

There happened something that I do not understand. Actually I don't even 
know how it can be possible.

I import a module and then the name space of the importing module seems do 
be overwritten.

my_name = __name__
print my_name
print len(dir())
from x import y as z
print __name__
print len(dir())
print my_name

->
__main__
119
x
117
unhandled NameError "name 'my_name' is not defined"

The module x is from me, and I am not aware of doing anything cruel there. 
What evil thing can be done in its sub module that can result in that 
strange thing?

br
Marco


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


Re: php to python code converter

2009-05-08 Thread D'Arcy J.M. Cain
On Fri, 8 May 2009 19:33:10 +0300
Dotan Cohen  wrote:
> It would be a great learning tool. I am pretty decent with PHP but
> just getting started in Python. This might help such users flatten out
> the learning curve.

If there were such a tool available I would sugegst it come with huge
warnings suggesting that the resulting code not be used for learning
purposes.  You would still be much better off with the tutorials.

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-08 Thread Gabriel Genellina
En Wed, 06 May 2009 23:32:23 -0300, Luis Alberto Zarrabeitia Gomez  
 escribió:




Quoting Steven D'Aprano :

But regardless, everyone is missing the most important point: why are  
you
copying and pasting code in the first place? That is surely very close  
to
the top of the list of Worst Ever Anti-Patterns, and it should be  
avoided

whenever possible.


[btw, I took this long before jumping into this thread for this precise
reason... Copy/paste is an evil anti-pattern.

In Python, we can avoid much copy-and-paste coding with decorators.  
Given
one function, we can create as many variants as we want, differing in  
pre-

processing of arguments and post-processing of results, by using
decorators. This is a powerful ability to have, but it's crippled for
many recursive functions, because recursive functions in Python don't
actually call themselves, they call whatever happens to be bound to  
their

name at runtime.


A bit offtopic: a while ago I think I saw a recipe for a decorator that,  
via
bytecode hacks, would bind otherwise global names to the local namespace  
of the
function. Can anyone remember it/point me to it? An @bind decorator that  
would
'localize' all the global names, including the still unexistent but  
already know
function name, would guarantee that at least recursion calls the same  
function
instead of "whatever happens to be bound to their name at runtime". If  
it wasn't

a hack, anyway.


I could not find such thing, but here it is something similar (mostly a  
proof-of-concept).
Basically, modifies the bytecode so global references become local ones,  
and then injects a new argument whose default value is the desired value.  
It can be used to make all references to the function name to refer to the  
function itself; also, the __function__ variant can be implemented.



from opcode import HAVE_ARGUMENT, opmap

def iter_code(co):
  """Iterate over a code object."""
  code = co.co_code
  n = len(code)
  i = 0
  while i < n:
op = ord(code[i])
if op >= HAVE_ARGUMENT:
  oparg = ord(code[i+1]) + ord(code[i+2])*256
  yield code[i:i+3], op, oparg
  i += 3
else:
  yield code[i], op, None
  i += 1

def replace_bytecode(code, iname_global, iname_local):
  LOAD_GLOBAL = opmap['LOAD_GLOBAL']
  LOAD_FAST = opmap['LOAD_FAST']
  STORE_GLOBAL = opmap['STORE_GLOBAL']
  STORE_FAST = opmap['STORE_FAST']
  for codestr, op, oparg in iter_code(code):
if op==LOAD_GLOBAL and oparg==iname_global:
  codestr = chr(LOAD_FAST) + chr(iname_local % 256) + chr(iname_local  
// 256)

elif op==STORE_GLOBAL and oparg==iname_global:
  codestr = chr(STORE_FAST) + chr(iname_local % 256) + chr(iname_local  
// 256)

yield(codestr)

class GlobalToLocalWarning(RuntimeWarning): pass

def global_to_local(function, refname, value):
  """
  Make all references to `refname` local instead of global.
  Actually, transform
def function(a,b,c):
  into
def function(a,b,c,refname=value)
  """
  code = function.func_code
  if refname not in code.co_names:
import warnings
warnings.warn(GlobalToLocalWarning('no reference to "%s" found in %s'  
% (refname, function.func_name)), stacklevel=2)

return function
  # insert refname just after the last argument
  varnames = list(code.co_varnames)
  varnames.insert(code.co_argcount, refname)
  # new bytecode using LOAD_FAST instead of LOAD_GLOBAL
  iname_global = code.co_names.index(refname) # LOAD_GLOBAL/STORE_GLOBAL  
operand

  iname_local = code.co_argcount # LOAD_FAST/STORE_FAST operand
  rawcode = ''.join(replace_bytecode(code, iname_global, iname_local))
  function.func_code = type(code)(
 code.co_argcount + 1,
 code.co_nlocals + 1,
 code.co_stacksize,
 code.co_flags,
 rawcode,
 code.co_consts,
 code.co_names,
 tuple(varnames),
 code.co_filename,
 code.co_name,
 code.co_firstlineno,
 code.co_lnotab
 )
  # the desired value is the default value of the new, fake argument
  if function.func_defaults is None:
function.func_defaults = (value,)
  else:
function.func_defaults += (value,)
  return function

# decorator: function name refers to itself
def recursive3(function):
  return global_to_local(function, function.func_name, function)

@recursive3
def fibo(n):
  if n<=1: return 1
  return fibo(n-1) + fibo(n-2)
  # those "fibo" won't be global anymore

# decorator: name '__function__' refers to function
def recursive4(function):
  return global_to_local(function, '__function__', function)

def factorial(n):
  @recursive4
  def _factorial(n, acc):
if n<=1: return acc
return __function__(n-1, n*acc)
  return _factorial(n, 1)

print fibo, fibo.__name__, fibo.func_name, fibo.func_code.co_name
assert fibo(5)==8
F10=factorial(10)
assert F10==2*3*4*5*6*7*8*9*10

foo = fibo
bar = factorial
del fibo, factorial
assert foo(5)==8
assert bar(10)==F10

import inspect
assert inspect.getargspec(foo).defaults[0] is foo


--
Gabriel Genellina

--
http://mail.pyth

Re: subprocess.Popen howto?

2009-05-08 Thread norseman

Carl Banks wrote:

On May 7, 2:58 pm, norseman  wrote:

If you don't like a lot of typing that obscures the process,
take a look at os.Popen2  Pg.39 or so in Lib.pdf for 2.5.2
In this case - the popen3 is probably your best bet.

I took a test run on "subprocess" a few months ago. My review:
excessive typing to accomplish the simple.



Hmm, I won't argue that it can be excessive typing, but I think its
purpose isn't to accomplish the simple but to hit all the corners of
subprocesses.

What if you want os.system without the shell?  What if you want popen
with the shell?  On Windows what if I want a subprocess without a
console from a Python program in a console.  Stuff like that.


Shell?  You lost me.
Why would you even use Windows?  Just kidding.
  Build the TSR and Start from Python or the bootup autostart
  and use it from Python or whatever.
Those in Unix, put the " &" after the program name in the starter
  to get it to background. Be sure to use P_NOWAIT in the starter.


I still use os.system for Q&D stuff, but now use subprocess for
everything else since I prefer thorough to short and sweet.


As long as speed (volume vs time) isn't a problem - OK.




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


==

1)  That one has access to and can make for ones self choices is
  freedom.
2)  As far as forcing a 'do all' into use is concerned,
  especially at the expense of removing others choices
  (Python notes say subprocess is supplanting popen et al),
  well... that is dictitorial, anti-freedom.
3)  Consider this: a do all is as useful as driving a Ferrari on
  a Jeep Jamboree cross crountry race. Or chasing a Ferrari
  through paved mountain roads with a Jeep.  The SUV is
  supposed to be a "do all". Would you actually expect it to
  win either race?  After all, they are all "cars".
Use/create the proper tool for the job. I do not know any good mechanics 
that have a monkey-wrench (a crescent) in their tool box.  And all of 
them will tell you that the guy who picks one up and starts toward the 
car may be upset with the driver but he is not a mechanic.

(Wrong tool of choice. Besides, should not have been available. :)
(Use the long handle 1/2" socket drive ratchet. Weight, length and 
balance are just right. ;)


Everybody - Read #1 one more time and make it (speak out loud) "my way".
If the client is happy, who cares how it was done?  But don't force 
others   (Python admins taking notes?)


Steve

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


Re: How to debug this import problem?

2009-05-08 Thread Diez B. Roggisch
Iwan Vosloo wrote:

> Hi there,
> 
> We have a rather complicated program which does a bit of os.chdir and
> sys.path manipulations.  In between all of this, it imports the decimal
> module several times.
> 
> However, it imports a new instance of decimal sometimes.  (Which is a
> problem, since a decimal.Decimal (imported at point A) now is not the
> same as that imported somewhere else.
> 
> In trying to figure out what's happening, we've changed the code in
> decimal to print out id(sys) when decimal gets imported.  This also
> gives back different values at different times.  My suspicion is that
> when importing python tries to check sys.modules - but each time sys is
> a different sys already.
> 
> Any ideas of how we can gather more data to find out exactly what causes
> this? The path manipulations is a suspect, but unfortunately we cannot
> remove it.  If we can trace the problem from the import end though, we
> may be able to isolate the exact one which is the problem.
> 
> This code incidentally also runs in a virtualenv environment AND uses
> setuptools.  None of these complications can be removed...

Try putting an "import pdb; pdb.set_trace()" on top of the decimal module.
Then you can see whenever it gets imported new, and with "bt" get a
backtrace, and you can inspect (and thus eventually compare) the various
states of sys.path and sys.modules.

Diez

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


Re: php to python code converter

2009-05-08 Thread Diez B. Roggisch
Dotan Cohen wrote:

>> I'm not a big fan of PHP but I don't understand the desireability of
>> such a tool.  If you have a good PHP app just run it.  The point of
>> Python in my mind is that it is a cleaner syntax and promotes better
>> code.  Anything that converts PHP to Python is going to leave you with
>> some butt-ugly Python.  It also risks adding new bugs.
>>
>> If you want a Python version of Drupal then perhaps that is the project
>> that you want to start.  Start fresh using the existing project as your
>> requirements specification.  Don't automatically import all their
>> coding choices that may be partially based on the language used.
>>
> 
> It would be a great learning tool. I am pretty decent with PHP but
> just getting started in Python. This might help such users flatten out
> the learning curve.

I'm almost 100% sure it won't. The code is machine-generated, thus not easy
to the human eye, not idiomatic so you don't learn how to write good python
through it. You learn how to jump through hoops to code the same way in
python that you do in PHP.

Diez

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


Re: php to python code converter

2009-05-08 Thread Dotan Cohen
> I'm almost 100% sure it won't. The code is machine-generated, thus not easy
> to the human eye, not idiomatic so you don't learn how to write good python
> through it. You learn how to jump through hoops to code the same way in
> python that you do in PHP.
>

I meant for single functions, not for translating entire apps.

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
--
http://mail.python.org/mailman/listinfo/python-list


Re: FLV download script works, but I want to enhance it

2009-05-08 Thread The Music Guy
On Thu, May 7, 2009 at 9:29 AM, Aahz  wrote:
>
> Here's my download script to get you started figuring this out, it does
> the wget in the background so that several downloads can run in parallel
> from a single terminal window:
>
> #!/bin/bash
>
> echo "Downloading $1"
> wget "$1" > /dev/null 2>&1 &
> --
> Aahz (a...@pythoncraft.com)           <*>         http://www.pythoncraft.com/
>
> "It is easier to optimize correct code than to correct optimized code."
> --Bill Harlan
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Aahz,

Thanks for the reply, but unfortunately that script is going in the
complete wrong direction.

Firstly, downloading multiple files in tandem does not speed up the
process as it merely cuts up the already limited bandwidth into even
smaller pieces and delays every download in progress. It is much
better to queue downloads to occur one-by-one.

Secondly, that approach is based on bash rather than Python. I know I
could use the `&` operator on a command line to background processes,
but I would like to be able to have more control through Python and
the use of the subprocess or threading modules.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to debug this import problem?

2009-05-08 Thread Scott David Daniels

Diez B. Roggisch wrote:

Iwan Vosloo wrote:

We have a rather complicated program which does a bit of os.chdir and
sys.path manipulations.  In between all of this, it imports the decimal
module several times
However, it imports a new instance of decimal sometimes.  (Which is a
problem, since a decimal.Decimal (imported at point A) now is not the
same as that imported somewhere else

In trying to figure out what's happening, we've changed the code in
decimal to print out id(sys) when decimal gets imported.  This also
gives back different values at different times.  My suspicion is that
when importing python tries to check sys.modules - but each time sys is
a different sys already.

Any ideas of how we can gather more data to find out exactly what causes
this? The path manipulations is a suspect, but unfortunately we cannot
remove it.  If we can trace the problem from the import end though, we
may be able to isolate the exact one which is the problem.

This code incidentally also runs in a virtualenv environment AND uses
setuptools.  None of these complications can be removed...


Try putting an "import pdb; pdb.set_trace()" on top of the decimal module.
Then you can see whenever it gets imported new, and with "bt" get a
backtrace, and you can inspect (and thus eventually compare) the various
states of sys.path and sys.modules.



You can also run Python with the "-v" or "-vv" flags to get output
about exactly what files are getting imported from the file
system and when.  "-v" iswhat it got, "-vv" is everywhere it tries.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: unicode bit me

2009-05-08 Thread Terry Reedy

Scott David Daniels wrote:


It would be a bit easier if people would bother to mention
their Python version, as we regularly get questions from people
running 2.3, 2.4, 2.5, 2.6, 2.7a, 3.0, and 3.1b.  They run computers
with differing operating systems and versions such as: Windows 2000,
OS/X Leopard, ubuntu Hardy Heron, SuSE, 


And if they copy and paste the actual error messages instead of saying 
'It doesn't work'


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


Re: import overwrites __name__

2009-05-08 Thread Terry Reedy

Marco wrote:

Hi,

There happened something that I do not understand. Actually I don't even 
know how it can be possible.


I import a module and then the name space of the importing module seems do 
be overwritten.


my_name = __name__
print my_name
print len(dir())
from x import y as z
print __name__
print len(dir())
print my_name

->
__main__
119
x
117
unhandled NameError "name 'my_name' is not defined"

The module x is from me, and I am not aware of doing anything cruel there. 
What evil thing can be done in its sub module that can result in that 
strange thing?


see responses to "unicode bit me' thread

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


ECG segmentation

2009-05-08 Thread Filip Gruszczyński
Hi!

I need to create a script, that performs ECG segmentation, but I can
hardly find any useful materials on the web. Did anyone try to do this
and could point me to some good materials/snippets about this?

-- 
Filip Gruszczyński
--
http://mail.python.org/mailman/listinfo/python-list


Re: unicode bit me

2009-05-08 Thread J. Cliff Dyer
On Fri, 2009-05-08 at 07:53 -0700, anuraguni...@yahoo.com wrote:
> #how can I print a list of object which may return unicode
> representation?
> # -*- coding: utf-8 -*-
> 
> class A(object):
> 
> def __unicode__(self):
> return u"©au"
> 
> __str__ = __repr__ = __unicode__
> 

Your __str__ and __repr__ methods don't return strings.  You should
encode your unicode to the encoding you want before you try to print it.

class A(object):
def __unicode__(self):
return u"©au"

def get_utf8_repr(self):
return self.__unicode__().encode('utf-8')

def get_koi8_repr(self):
return self.__unicode__().encode('koi-8')

__str__ = __repr__ = self.get_utf8_repr

> a = A()
> 
> try:
> print a # doesn't work?
> except UnicodeEncodeError,e:
> print e
> try:
> print unicode(a) # works, ok fine, great
> except UnicodeEncodeError,e:
> print e
> try:
> print unicode([a]) # what doesn't work?
> except UnicodeEncodeError,e:
> print e
> """
> Now how can I print a list of object which may return unicode
> representation?
> loop/map is not an option as it goes much deepr in my real code
> any can anyoen explain what is happening here under the hood?
> """
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

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


I'm intrigued that Python has some functional constructions in the language.

2009-05-08 Thread Casey Hawthorne
I'm intrigued that Python has some functional constructions in the
language.

Would it be possible to more clearly separate the pure code (without
side effects) from the impure code (that deals with state changes,
I/O, etc.), so that the pure code could be compiled and have
aggressive functional transformations applied to it for efficiency.

That way, the syntax would be a lot easier to understand, than most
functional languages, like Haskell.

I gave a presentation at the beginning of last year on Haskell and at
the end, someone's comment was, "I can see the benefits of functional
programming but why does it have to be so cryptic."
--
Regards,
Casey
--
http://mail.python.org/mailman/listinfo/python-list


Re: php to python code converter

2009-05-08 Thread J. Cliff Dyer
On Fri, 2009-05-08 at 17:19 +0200, Pascal Chambon wrote:
> PS : Am I the only one having most of answers rejected by the
> antispam 
> system of python-list ? That's humiliating :p
> 

I've had several messages not make it through.

:(


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


Re: ECG segmentation

2009-05-08 Thread CTO
On May 8, 2:04 pm, Filip Gruszczyński  wrote:
> Hi!
>
> I need to create a script, that performs ECG segmentation, but I can
> hardly find any useful materials on the web. Did anyone try to do this
> and could point me to some good materials/snippets about this?
>
> --
> Filip Gruszczyński

How are you looking to do it? If you want an HMM-based solution I'd
recommend http://ghmm.sourceforge.net/ghmm-python-tutorial.html>.

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


Re: I'm intrigued that Python has some functional constructions in the language.

2009-05-08 Thread pruebauno
On May 8, 3:04 pm, Casey Hawthorne  wrote:
> I'm intrigued that Python has some functional constructions in the
> language.
>
> Would it be possible to more clearly separate the pure code (without
> side effects) from the impure code (that deals with state changes,
> I/O, etc.), so that the pure code could be compiled and have
> aggressive functional transformations applied to it for efficiency.
>
> That way, the syntax would be a lot easier to understand, than most
> functional languages, like Haskell.
>
> I gave a presentation at the beginning of last year on Haskell and at
> the end, someone's comment was, "I can see the benefits of functional
> programming but why does it have to be so cryptic."
> --
> Regards,
> Casey

Don't forget that the Python interpreter is simple. It makes
maintenance easier and allows embedding it into other programs. Good
optimizing compilers for functional languages are not simple. Your
idea would be something that could be added to the PyPy project in the
future.
--
http://mail.python.org/mailman/listinfo/python-list


Re: I'm intrigued that Python has some functional constructions in the language.

2009-05-08 Thread Carl Banks
On May 8, 12:04 pm, Casey Hawthorne 
wrote:
> I'm intrigued that Python has some functional constructions in the
> language.
>
> Would it be possible to more clearly separate the pure code (without
> side effects) from the impure code (that deals with state changes,
> I/O, etc.), so that the pure code could be compiled and have
> aggressive functional transformations applied to it for efficiency.

No not really, at least not in any way that it maintains compatibility
with Python.

Python does either expose or mimic the parsing process to the user, so
you could maybe exploit it to get parse trees of functions (checking
that there is nothing that has side-effects) to feed to a specialized
optimizer, but if you do that it might as well be a new langauge.


> That way, the syntax would be a lot easier to understand, than most
> functional languages, like Haskell.
>
> I gave a presentation at the beginning of last year on Haskell and at
> the end, someone's comment was, "I can see the benefits of functional
> programming but why does it have to be so cryptic."

A couple thoughts:

1. It's just one person's opinion.
2. However, functional programming is cryptic at some level no matter
how nice you make the syntax.


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


Re: import overwrites __name__

2009-05-08 Thread Marco
Terry Reedy wrote:

> Marco wrote:
>> Hi,
>> 
>> There happened something that I do not understand. Actually I don't even
>> know how it can be possible.
>> 
>> I import a module and then the name space of the importing module seems
>> do be overwritten.
>> 
>> my_name = __name__
>> print my_name
>> print len(dir())
>> from x import y as z
>> print __name__
>> print len(dir())
>> print my_name
>> 
>> ->
>> __main__
>> 119
>> x
>> 117
>> unhandled NameError "name 'my_name' is not defined"
>> 
>> The module x is from me, and I am not aware of doing anything cruel
>> there. What evil thing can be done in its sub module that can result in
>> that strange thing?
> 
> see responses to "unicode bit me' thread

Therry,

What shall I find there?



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


Complete frustration

2009-05-08 Thread hellcats
I have Python2.5 installed on Windows XP. Whenever I double click on a
something.pyw file, IDLE launches and opens something.pyw in the
editor. I would prefer to actually *RUN* the program, not edit it. If
I want to edit it then I'll choose the "Edit with IDLE" context menu.
So I then have to press F5 to get the program to execute. Now I have
my program's windows along with two IDLE windows cluttering my screen
and task bar. WHAT IS GOING ON? I've tried changing the file
association to python.exe, and that works, but just ONCE (even if I
choose "always use the slected program to launch this kind of file").
IDLE may be great and all, but I fricken' don't want to see it every
time I just want to run a python program!
--
http://mail.python.org/mailman/listinfo/python-list


Re: I'm intrigued that Python has some functional constructions in the language.

2009-05-08 Thread namekuseijin

prueba...@latinmail.com escreveu:

Don't forget that the Python interpreter is simple. It makes
maintenance easier and allows embedding it into other programs. Good
optimizing compilers for functional languages are not simple.


Good optimizing compilers are not simple, period.

The python interpreter is not all that simple either.  Have you ever 
taken a look at it?  It's a good bytecode interpreter, not some dumb toy 
interpreter.


--
a game sig: http://tinyurl.com/d3rxz9
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >