Re: gui application on cross platform

2007-05-28 Thread Stefano Canepa
On 28 Mag, 08:01, james_027 <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I am using delphi to develop gui application, and wish to make a shift
> to python. here are some of my question/concern...
>
> 1. is python develop gui application a cross platform? just like java
> swing?

Yes. Qt, wxwidgets and pygtk run on Linux and Windows, don't know
about Macs.

> 2. delphi makes things easy for me like coding for a specific event on
> a specific component, could it be the same for python?

Not in the Delphi way but glade/gazpacho are good GUI designer for
gtk.
I have no experience with qtdesigner or the wx equivalent app.

> 3. are there cool library of component like in delphi available for
> python that will make database application more usesable?

python has dbapi, all DBs look the same, python can also use ORM like
SQLObjects and SQLALchemy

> 4. where do I start the learning curve? I did some research and I
> don't know which one to take among wxwdiget, pygtk, and etc.

I tried wxwidgets and pygtk, then I decided to use pygtk but it
could be I'll change my mind in the future.

Bye
sc

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


Re: Error in optparse documentation

2007-05-28 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Shatadal
wrote:

> I think the documentation should be modified so that it is made clear
> that %default in the help string behaves as is claimed only in version
> 2.4 and higher.

Maybe something should be added for clarity but I don't think it's an
error in the docs.  You are reading documentation for Python 2.5 and
expect everything in it to work in older versions too?

Pick the right documentation from http://www.python.org/doc/versions/

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can python create a dictionary from a list comprehension?

2007-05-28 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, half.italian
wrote:

> [entries.__setitem__(int(d.date.strftime('%m'))], d.id) for d in
> links]
> 
> btw...I was curious of this too.  I used 'dir(dict)' and looked for a
> method that might do what we wanted and bingo!

This is really ugly.  Except `__init__()` it's always a code smell if you
call a "magic" method directly instead of using the corresponding
syntactic sugar or built in function.  And using a list comprehension just
for side effects is misleading because the reader expects a (useful) list
to be build when stumbling over a list comp and it's wasteful because an
unnecessary list of `None`\s is build and thrown away for no reason other
than to have a one liner.  This is not Perl!  ;-)

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: gui application on cross platform

2007-05-28 Thread james_027
On May 28, 3:06 pm, Stefano Canepa <[EMAIL PROTECTED]> wrote:
> On 28 Mag, 08:01, james_027 <[EMAIL PROTECTED]> wrote:
>
> > Hi,
>
> > I am using delphi to develop gui application, and wish to make a shift
> > to python. here are some of my question/concern...
>
> > 1. is python develop gui application a cross platform? just like java
> > swing?
>
> Yes. Qt, wxwidgets and pygtk run on Linux and Windows, don't know
> about Macs.
>
> > 2. delphi makes things easy for me like coding for a specific event on
> > a specific component, could it be the same for python?
>
> Not in the Delphi way but glade/gazpacho are good GUI designer for
> gtk.
> I have no experience with qtdesigner or the wx equivalent app.
>
> > 3. are there cool library of component like in delphi available for
> > python that will make database application more usesable?
>
> python has dbapi, all DBs look the same, python can also use ORM like
> SQLObjects and SQLALchemy
>
> > 4. where do I start the learning curve? I did some research and I
> > don't know which one to take among wxwdiget, pygtk, and etc.
>
> I tried wxwidgets and pygtk, then I decided to use pygtk but it
> could be I'll change my mind in the future.
>
> Bye
> sc

Thanks sc,

What do you mean when you say .."all DBs look the same"

what is the difference between pygtk and wxwidgets?

bye
james

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


Re: Newbie question - better way to do this?

2007-05-28 Thread Nis Jørgensen
Steve Howell skrev:

> def firstIsCapitalized(word):
> return 'A' <= word[0] <= 'Z'

For someone who is worried about the impact of non-ascii identifiers,
you are making surprising assumptions about the contents of data.

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


Re: Can python create a dictionary from a list comprehension?

2007-05-28 Thread Wim Vogelaar
> Example:
>
> a = [1,2,3,4,5,6,7,8,9,10]
>
> aDict = dict([(x,x+1) for x in a if x%2==0])
>
> print aDict
>

When I run this program I get:
{8: 9, 2: 3, 4: 5, 10: 11, 6: 7}

why this output isn't ordered, giving:
{2: 3, 4: 5, 6: 7, 8: 9, 10: 11 }



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


Re: Can python create a dictionary from a list comprehension?

2007-05-28 Thread Maric Michaud
Pierre Quentel a écrit :
> On 27 mai, 22:55, erikcw <[EMAIL PROTECTED]> wrote:
>> Hi,
>>
>> I'm trying to turn o list of objects into a dictionary using a list
>> comprehension.
...
> 
> entries = dict([ (int(d.date.strftime('%m')),d.id) for d in links] )
> 
> With Python2.4 and above you can use a "generator expression"
> 
> entries = dict( (int(d.date.strftime('%m')),d.id) for d in links )
> 

You can also create dictionaries knowing only the keys the same way (ie. 
a two-dimensional array) :

In [77]: dict.fromkeys((a, b) for a in range(4) for b in range(2))
Out[78]:
{(0, 0): None,
  (0, 1): None,
  (1, 0): None,
  (1, 1): None,
  (2, 0): None,
  (2, 1): None,
  (3, 0): None,
  (3, 1): None}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is PEP-8 a Code or More of a Guideline?

2007-05-28 Thread Maric Michaud
Ben Finney a écrit :
> Paul McGuire <[EMAIL PROTECTED]> writes:
> 
>> It is a bit reassuring that I am not the only one who turns a blind
>> eye to this part of the PEP, that l_c_w_u bothers others as well.
> 
> I see similar support for lower_case, and opposition to
> camelCase. It's nice that we're both reassured by what we see. What
> now?
> 

So it's actually a matter of taste, and that's why PEP 8 exists, to
answer the subject's question, make decision about conventions when only
taste is in balance, am I wrong ?

Asking the question is like asking : "I don't like the convention, can I
use another one for myself ?" I think the answer is, of course, yes, but
it is highly discouraged... (and that's why PEP 8 exists after all).

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


Re: os.path.walk not pruning descent tree (and I'm not happy with that behavior?)

2007-05-28 Thread Maric Michaud
I'm really sorry, for all that private mails, thunderbird is awfully 
stupid dealing with mailing lists folder.


Gabriel Genellina a écrit :
> En Sun, 27 May 2007 22:39:32 -0300, Joe Ardent <[EMAIL PROTECTED]> escribió:
> 
> 
> - iterate backwards:
> 
> for i in range(len(names)-1, -1, -1):
>fname = names[i]
>if fname[:1]=='.':
>  names.remove(fname)
> 

This is not about iterating backward, this is about iterating over the
index of each element instead of iterating over the element (which must
be done begining by the end). In fact this code is both inefficient and
contains a subtle bug. If two objects compare equals in the list, you
will remove the wrong one.

It should be :

for i in range(len(names)-1, -1, -1):
if names[i][:1]=='.':
  del names[i]


> - filter and reassign in place 

Seems the best here.

> (the [:] is important):

Not so. Unless "names" is referenced in another namespace, simple
assignment is enough.

> names[:] = [fname for fname in names if fname[:1]!='.']
> 
> (Notice that I haven't used a regular expression, and the remove method)
> 


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


Flags of the world

2007-05-28 Thread Tim Churches
http://shaheeilyas.com/flags/

Scroll to the bottom to see why this is not entirely off-topic. Are
there other public examples in which Python has been used to harvest and
represent public information in useful and/or interesting ways? Ideas
for some more?

Tim C


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


Re: gui application on cross platform

2007-05-28 Thread Gabriel Genellina
En Mon, 28 May 2007 04:28:50 -0300, james_027 <[EMAIL PROTECTED]>  
escribió:

> I am using delphi to develop gui application, and wish to make a shift
> to python. here are some of my question/concern...

Explore the Python wiki, specially  
 and ChoosingGuiToolkits.
Here you have and "Intelligent GUI chooser"  

Search previous posts on this group too as this is a recurring topic.

-- 
Gabriel Genellina

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


Re: unit testing

2007-05-28 Thread Nis Jørgensen
Steve Howell skrev:

> And, really, if
> you're not doing automated tests on your application
> now, you don't know what you're missing.

Quote of the day, IMO.

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


Re: Can python create a dictionary from a list comprehension?

2007-05-28 Thread Gabriel Genellina
En Mon, 28 May 2007 05:20:16 -0300, Wim Vogelaar  
<[EMAIL PROTECTED]> escribió:

>> Example:
>>
>> a = [1,2,3,4,5,6,7,8,9,10]
>>
>> aDict = dict([(x,x+1) for x in a if x%2==0])
>>
>> print aDict
>>
>
> When I run this program I get:
> {8: 9, 2: 3, 4: 5, 10: 11, 6: 7}
>
> why this output isn't ordered, giving:
> {2: 3, 4: 5, 6: 7, 8: 9, 10: 11 }

A dictionary is not ordered, no matter how you create it. If you want to  
process the keys in order:

for key in sorted(aDict):
   print key, '=', aDict[key]

(Note that sorted(aDict) returns a *list*, not a dictionary!)

-- 
Gabriel Genellina

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


Re: Can python create a dictionary from a list comprehension?

2007-05-28 Thread Wim Vogelaar

>
> why this output isn't ordered, giving:
> {2: 3, 4: 5, 6: 7, 8: 9, 10: 11 }
>
>

I made the original list two elements longer: a = 
[1,2,3,4,5,6,7,8,9,10,11,12]

and to my surprise the output is now ordered, giving: {2: 3, 4: 5, 6: 7, 8: 
9, 10: 11, 12: 13}

I am running ActiveState ActivePython 2.5

 


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


Re: os.path.walk not pruning descent tree (and I'm not happy with that behavior?)

2007-05-28 Thread Gabriel Genellina
En Mon, 28 May 2007 05:25:18 -0300, Maric Michaud <[EMAIL PROTECTED]>  
escribió:

> Gabriel Genellina a écrit :
>> - iterate backwards:
>>
>> for i in range(len(names)-1, -1, -1):
>>fname = names[i]
>>if fname[:1]=='.':
>>  names.remove(fname)
>>
>
> This is not about iterating backward, this is about iterating over the
> index of each element instead of iterating over the element (which must
> be done begining by the end). In fact this code is both inefficient and
> contains a subtle bug. If two objects compare equals in the list, you
> will remove the wrong one.
>
> It should be :
>
> for i in range(len(names)-1, -1, -1):
> if names[i][:1]=='.':
>   del names[i]

Yes, sure, this is what I should have written. Thanks for the correction!

>> - filter and reassign in place
>
> Seems the best here.
>
>> (the [:] is important):
>
> Not so. Unless "names" is referenced in another namespace, simple
> assignment is enough.

But this is exactly the case; the visit function is called from inside the  
os.path.walk code, and you have to modify the names parameter in-place for  
the caller to notice it (and skip the undesided files and folders).

-- 
Gabriel Genellina

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


Sci.linalg.lu permuation error

2007-05-28 Thread Luke
I'm trying to use Scipy's LU factorization.  Here is what I've got:

from numpy import *
import scipy as Sci
import scipy.linalg

A=array([[3., -2., 1., 0., 0.],[-1., 1., 0., 1., 0.],[4., 1., 0., 0.,
1.]])
p,l,u=Sci.linalg.lu(A,permute_l = 0)

now, according to the documentation:
**
Definition: Sci.linalg.lu(a, permute_l=0, overwrite_a=0)
Docstring:
Return LU decompostion of a matrix.

Inputs:

  a -- An M x N matrix.
  permute_l  -- Perform matrix multiplication p * l [disabled].

Outputs:

  p,l,u  -- LU decomposition matrices of a [permute_l=0]
  pl,u   -- LU decomposition matrices of a [permute_l=1]

Definitions:

  a = p * l * u[permute_l=0]
  a = pl * u   [permute_l=1]

  p   -  An M x M permutation matrix
  l   -  An M x K lower triangular or trapezoidal matrix
 with unit-diagonal
  u   -  An K x N upper triangular or trapezoidal matrix
 K = min(M,N)
*


So it would seem that from my above commands, I should have:
A == dot(p,dot(l,u))

but instead, this results in:
In [21]: dot(p,dot(l,u))
Out[21]:
array([[-1.,  1.,  0.,  1.,  0.],
   [ 4.,  1.,  0.,  0.,  1.],
   [ 3., -2.,  1.,  0.,  0.]])

Which isn't equal to A!!!
In [23]: A
Out[23]:
array([[ 3., -2.,  1.,  0.,  0.],
   [-1.,  1.,  0.,  1.,  0.],
   [ 4.,  1.,  0.,  0.,  1.]])

However, if I do use p.T instead of p:
In [22]: dot(p.T,dot(l,u))
Out[22]:
array([[ 3., -2.,  1.,  0.,  0.],
   [-1.,  1.,  0.,  1.,  0.],
   [ 4.,  1.,  0.,  0.,  1.]])

I get the correct answer.

Either the documentation is wrong, or somehow Scipy is returning the
wrong permutation matrix... anybody have any experience with this or
tell me how to submit a bug report?

Thanks.
~Luke

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


Re: Can python create a dictionary from a list comprehension?

2007-05-28 Thread half . italian
On May 28, 12:25 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> In <[EMAIL PROTECTED]>, half.italian
> wrote:
>
> > [entries.__setitem__(int(d.date.strftime('%m'))], d.id) for d in
> > links]
>
> > btw...I was curious of this too.  I used 'dir(dict)' and looked for a
> > method that might do what we wanted and bingo!
>
> This is really ugly.  Except `__init__()` it's always a code smell if you
> call a "magic" method directly instead of using the corresponding
> syntactic sugar or built in function.  And using a list comprehension just
> for side effects is misleading because the reader expects a (useful) list
> to be build when stumbling over a list comp and it's wasteful because an
> unnecessary list of `None`\s is build and thrown away for no reason other
> than to have a one liner.  This is not Perl!  ;-)
>
> Ciao,
> Marc 'BlackJack' Rintsch

It's ugly I agree, but it was the first solution I found.  I need you
guys for the _right_ solutions :)  I have stumbled over the same
situation myself.  I don't see that the list comprehension itself is
misleading.  If nothing is catching the empty list that is returned,
it signals that the returned list is unimportant, and if wrapped by a
call to dict() its obvious also.

Do you think we just shouldn't use list comprehensions to build
dictinaries at all? Or is Stefan's solution acceptable (and pythonic)?

~Sean

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


Re: What's the best way to iniatilize a function

2007-05-28 Thread Gregor Horvath
Jack schrieb:

> I didn't call del explicitly. I'm expecting Python to call it when
> the program exits. I put a logging line in __del__() but I never
> see that line printed. It seems that __del__() is not being called
> even when the program exits. Any idea why?
> 
> 

http://effbot.org/pyfaq/my-class-defines-del-but-it-is-not-called-when-i-delete-the-object.htm

better solutions:

http://docs.python.org/ref/try.html
http://docs.python.org/whatsnew/pep-343.html

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


Re: gui application on cross platform

2007-05-28 Thread Matt van de Werken
james_027 wrote:
> Hi,
> 
> I am using delphi to develop gui application, and wish to make a shift
> to python. here are some of my question/concern...
> 
> 1. is python develop gui application a cross platform? just like java
> swing?
> 2. delphi makes things easy for me like coding for a specific event on
> a specific component, could it be the same for python?
> 3. are there cool library of component like in delphi available for
> python that will make database application more usesable?
> 4. where do I start the learning curve? I did some research and I
> don't know which one to take among wxwdiget, pygtk, and etc.
> 
> 

I'm also going down this path, and have decided on python + wxWidgets + 
boa as the RAD tool.  From the tutorial, it seems pretty easy to use, 
except for some minor annoyances on both windows and linux platforms.

Under windows, for some inexplicable reason the "dialogs" tab is not 
present, while under linux, I can't seem to drag components around the 
frame after placement.

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


Re: Can python create a dictionary from a list comprehension?

2007-05-28 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> Do you think we just shouldn't use list comprehensions to build
> dictinaries at all? Or is Stefan's solution acceptable (and pythonic)?

Use list comprehensions where you need the resulting list; if you want
nothing but the side effects, use a for loop.

[Stefan Sonnenberg-Carstens]
> a = [1,2,3,4,5,6,7,8,9,10]
> aDict = dict([(x,x+1) for x in a if x%2==0])

Stefan's example meets the above criterion, so yes, it's acceptable. In
Python 2.5 you would use a generator expression, though:

aDict = dict((x, x+1) for x in a if x % 2 ==0)

Peter

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


Re: Can python create a dictionary from a list comprehension?

2007-05-28 Thread Gabriel Genellina
En Mon, 28 May 2007 05:37:12 -0300, Wim Vogelaar  
<[EMAIL PROTECTED]> escribió:

> I made the original list two elements longer: a =
> [1,2,3,4,5,6,7,8,9,10,11,12]
>
> and to my surprise the output is now ordered, giving: {2: 3, 4: 5, 6: 7,  
> 8:
> 9, 10: 11, 12: 13}
>
> I am running ActiveState ActivePython 2.5

Keys in a dictionary are listed in an arbitrary order; the *only* thing  
about the ordering you can say is that, given a FIXED dictionary (already  
constructed, and without any other intervening operation that could alter  
its content), when you iterate over its keys (using .keys(), .iterkeys()),  
its values (.values(), .itervalues()) or items (.items(), .iteritems())  
you will always get the same things in the same order over and over.
If you create the dictionary using a different sequence of insertions and  
deletions, you may get different results. If you insert and delete things  
afterwards, you may get different results. If you exit the program and run  
it again, you may get different results. The *only* guaranteed fact is  
that you will get the same results provided you don't modify the  
dictionary at all.

See note (3) in http://docs.python.org/lib/typesmapping.html

-- 
Gabriel Genellina

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


Issue of redirecting the stdout to both file and screen

2007-05-28 Thread 人言落日是天涯,望极天涯不见家
I wanna print the log to both the screen and file, so I simulatered a
'tee'

class Tee(file):

def __init__(self, name, mode):
file.__init__(self, name, mode)
self.stdout = sys.stdout
sys.stdout = self

def __del__(self):
sys.stdout = self.stdout
self.close()

def write(self, data):
file.write(self, data)
self.stdout.write(data)

Tee('logfile', 'w')
print >>sys.stdout, 'abcdefg'

I found that it only output to the file, nothing to screen. Why?
It seems the 'write' function was not called when I *print* something.

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

Re: Unsubscribing from the mailing list

2007-05-28 Thread Ben Finney
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> I do not know if this is the correct group to ask this question. But
> since mailman is python-based I thought i would ask here.

There are a great many Python-based applications; this forum is for
discussing the Python language and closely-related topics.

Mailman has its own support resources that will better be able to
answer your questions:

http://list.org/>

-- 
 \  "...one of the main causes of the fall of the Roman Empire was |
  `\that, lacking zero, they had no way to indicate successful |
_o__)   termination of their C programs."  -- Robert Firth |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unsubscribing from the mailing list

2007-05-28 Thread Tina I
[EMAIL PROTECTED] wrote:
> Hi All,
> 
> I do not know if this is the correct group to ask this question. But
> since mailman is python-based I thought i would ask here.
> 
> I had subscribed to a mailing list called [EMAIL PROTECTED]
> adventitiously. I then wanted to reverse my decision and so tried to
> unsubscribe from the mailing list. The web interface told that I had
> to enter my username and then click unsubscribe. I did so. I was
> responded with the message that "A confirmation mail has been sent".
> However I did not get any mail of that sort. Due to this I am not able
> to unsubscribe and I get loads of emails from that mailing list every
> day.
> 
> Can somebody help me get out of this mess??
> 
> Thanks,
> Sundar
> 
Umm... why not ask on [EMAIL PROTECTED] ??
-- 
http://mail.python.org/mailman/listinfo/python-list


xmlrpclib hangs execution

2007-05-28 Thread Arno Stienen
Perhaps I should be a bit more specific. When using this code to connect 
to a remote XML-RPC server (C++, xmlrpc++0.7 library):

   import xmlrpclib
   server = xmlrpclib.Server("http://10.10.101.62:29500";)
   print server.Connection_Request("roberto")

the Python command line 'hangs' until I kill the server. Then, the 
correct output is suddenly displayed:

   {'state': 0, 'id_session': '2Z3EUSLJFA13', 'port': 29501,
   'str': 'Connection accepted. Session attached.'}

Yet a slightly simpler call works flawlessly:

   import xmlrpclib
   server = xmlrpclib.Server("http://10.10.101.62:29500";)
   print server.Info_RT('Master')

   {'state': 0, 'str': 'Info_RT'}

Looking at the TCP packages (using Wireshark), the first 
Connection_Request flow as follows (c=python client,s= xml-rpcserver):

  1 c>s SYN
  2 s>c SYN,ACK
  3 c>s ACK
  4 c>s PSH,ACK (setting content-type: text/xml)
  5 s>c ACK
  6 c>s PSH,ACK (xml-rpc request)
  7 s>c ACK
  8 s>c PSH,ACK (xml-rpc results, correct)
  9 c>s ACK

At this point, Python 'hangs' until I kill (-9) the server (28 seconds 
later), and then these last packages are send:

10  s>c FIN,ACK
11  c>s FIN,ACk
12  s>c ACK

After which Python continues and prints the xml-rpc results on the 
screen. Strangely, before Python hangs, it has already received the 
package with the results, but doesn't do anything with it.

For comparison, this is the package flow for the Info_RT method, which 
returns within a second with the correct result on the Python command line:

  1 c>s SYN
  2 s>c SYN,ACK
  3 c>s ACK
  4 c>s PSH,ACK (setting content-type: text/xml)
  5 s>c ACK
  6 c>s PSH,ACK (xml-rpc request)
  7 s>c ACK
  8 s>c PSH,ACK (xml-rpc results, correct)
  9 s>c FIN,ACK
10  c>s ACK
11  c>s FIN,ACk
12  s>c ACK

Notice the reverse order of packages 9 and 10. Could this be it? Is 
Python waiting until the server sends a FIN package? But if so, why?

Looking at the Python trace, this might be it. A diff between the trace 
of the killed Connection_Request and the Info_RT resulted only in 
expected differences (due to different length of parameters). But when 
diffing the traces of the killed and non-killed Connection_Request, 
something else is visible. The killed Connection_Request ends with:

[...]
string:318: return sep.join(words)
xmlrpclib:866: self._type = "params"
xmlrpclib:769: try:
xmlrpclib:770: f = self.dispatch[tag]
xmlrpclib:771: except KeyError:
xmlrpclib:772: pass # unknown tag ?
xmlrpclib:1273: if sock:
xmlrpclib:1274: response = sock.recv(1024)
xmlrpclib:1277: if not response:
xmlrpclib:1278: break
xmlrpclib:1283: file.close()
socket:218: try:
socket:219: if self._sock:
socket:220: self.flush()
socket:232: if self._wbuf:
socket:222: self._sock = None
xmlrpclib:1284: p.close()
xmlrpclib:530: self._parser.Parse("", 1) # end of data
xmlrpclib:531: del self._target, self._parser # get rid of 
circular references
xmlrpclib:1286: return u.close()
xmlrpclib:741: if self._type is None or self._marks:
xmlrpclib:743: if self._type == "fault":
xmlrpclib:745: return tuple(self._stack)
socket:225: try:
socket:226: self.close()
socket:218: try:
socket:219: if self._sock:
socket:222: self._sock = None
xmlrpclib:1386: if len(response) == 1:
xmlrpclib:1387: response = response[0]
xmlrpclib:1389: return response
__main__:26: print result
{'state': 0, 'id_session': 'QDLY3GP9FBM5', 'port': 29501, 'str': 
'Connection accepted. Session attached.'}

But the non-killed Connection_Request looks like:

[...]
return sep.join(words)
xmlrpclib:866: self._type = "params"
xmlrpclib:769: try:
xmlrpclib:770: f = self.dispatch[tag]
xmlrpclib:771: except KeyError:
xmlrpclib:772: pass # unknown tag ?
xmlrpclib:1273: if sock:
xmlrpclib:1274: response = sock.recv(1024)
socket:225: try:
socket:226: self.close()
socket:218: try:
socket:219: if self._sock:
socket:220: self.flush()
socket:232: if self._wbuf:
socket:222: self._sock = None

(In the diff there is a gap between the xmlrpclib:1274 and socket:225 
lines, as compared to the killed Connection_Request; perhaps Ctrl+C 
still executes the "socket try close" lines?)

If you want to do your own 'diff' on the Python traces, or look at the 
TCP packages in more details with Wireshark, here are the files for the 
correctly working Info_RT 

stdout and threads

2007-05-28 Thread Troels Thomsen
Hello All

I have trouble printing to stdout from a thread and main program.

Not only will it look strange when they try to print at the same time, that 
is ok, but i think i see lock-ups. (strange exceptions in Tkinker etc) Or is 
it an issue with IDLE ?

Should I implement a lock'ed / queued version and hook it into the 
sys.stdout ?

(sorry if this has been answered recently in this group)

using
Python 2.5 (r25:51908
Idle 1.2

tpt



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


Re: conditionally creating functions within a class?

2007-05-28 Thread [EMAIL PROTECTED]
On 26 mai, 04:14, Steve Holden <[EMAIL PROTECTED]> wrote:
(snip)
> one of the primary ideas behind object
> orientation is that the class defines the same methods for all instances.
>

While this is effectively the standard behaviour in class-based OOPLs,
I would definitively not present this
as "one of the primary ideas behind" OO, since nothing in OO "primary
ideas" mandate the explicit of classes.


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


Re: python -- prolog bridge error

2007-05-28 Thread [EMAIL PROTECTED]
On May 27, 8:40 pm, yuce <[EMAIL PROTECTED]> wrote:
> Hello,
>
> PySWIP requires "libpl.dll" to be on the path. There are two ways to
> do this:
>
> 1) Add 'bin' directory of SWI-Prolog to the PATH (it's C:\Program Files
> \pl\bin on my system),
>
> 2) Or, copy 'libpl.dll' and 'pthreadVC.dll' to C:\WINDOWS\system32
>
> That should solve the problem, happy hacking :)
>
> Yuce Tekol
>
> On 27 Mayýs, 03:08, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>
>
>
> >  I am getting an error with pyswip on xp that says the .dll isn't
> > installed as a shared library.  Is there a manual way to install
> > the .dll as such???  prolog seems to work fine it is just the bridge
> > that gives an error- Hide quoted text -
>
> - Show quoted text -

I am not sure how to add it to the path...  I did get it to work and
now I have a interactive screen up...  I will have to look into the
docs to see if I can get it do anything else..

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


Re: Issue of redirecting the stdout to both file and screen

2007-05-28 Thread Peter Otten
人言落日是天涯,望极天涯不见家 wrote:

> I wanna print the log to both the screen and file, so I simulatered a
> 'tee'
> 
> class Tee(file):
> 
> def __init__(self, name, mode):
> file.__init__(self, name, mode)
> self.stdout = sys.stdout
> sys.stdout = self
> 
> def __del__(self):
> sys.stdout = self.stdout
> self.close()
> 
> def write(self, data):
> file.write(self, data)
> self.stdout.write(data)
> 
> Tee('logfile', 'w')
> print >>sys.stdout, 'abcdefg'
> 
> I found that it only output to the file, nothing to screen. Why?
> It seems the 'write' function was not called when I *print* something.

There are places in the C code of Python that do the equivalent of

if isinstance(file_like_object, file):
file.write(file_like_object, text)
else:
file_like_object.write(text)

Therefore you can't safely inherit from file. The workaround is to make your
own file-like object; yours would become

class Tee(object):
def __init__(self, name, mode):
self.file = open(name, mode)
self.stdout = sys.stdout
sys.stdout = self
def __del__(self):
sys.stdout = self.stdout
self.file.close()
def write(self, data):
self.file.write(data)
self.stdout.write(data)

Peter


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

Re: Can python create a dictionary from a list comprehension?

2007-05-28 Thread Duncan Booth
"Wim Vogelaar"  wrote:

> 
>>
>> why this output isn't ordered, giving:
>> {2: 3, 4: 5, 6: 7, 8: 9, 10: 11 }
>>
>>
> 
> I made the original list two elements longer: a = 
> [1,2,3,4,5,6,7,8,9,10,11,12]
> 
> and to my surprise the output is now ordered, giving: {2: 3, 4: 5, 6:
> 7, 8: 9, 10: 11, 12: 13}
> 
... and it will become unordered again when you get up to storing 32 in the 
dictionary, and ordered again when you get up to 44.

It is an unfortunate side-effect of the way that Python dictionaries work 
that it often appears when you store small integers as though they are 
being stored sorted. In fact the order depends on the order in which you 
inserted the values into the dictionary, the current size allocated to the 
dictionary, and whether any slots have previously been occupied by other 
values.

In your original output:

  {8: 9, 2: 3, 4: 5, 10: 11, 6: 7}

the keys 2, 4, and 6 are inserted into the 2nd, 4th, 6th slots of the 
dictionary (counting from 0 and there are initially 8 slots), 8 goes into 
the 0th slot, 10 would go into the 2nd slot except that is filled so it 
ends up in the 5th slot.

When you insert 12, the initial dictionary is too full (it never fills all 
the slots), so it is resized to have 32 slots. Again the 32 wraps round to 
the 0th slot and higher values all collide with filled slots so they end up 
in less obvious positions:

>>> for i in range(12,42,2):
print dict.fromkeys(range(2,i,2))


{8: None, 2: None, 4: None, 10: None, 6: None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16: 
None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16: 
None, 18: None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16: 
None, 18: None, 20: None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16: 
None, 18: None, 20: None, 22: None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16: 
None, 18: None, 20: None, 22: None, 24: None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16: 
None, 18: None, 20: None, 22: None, 24: None, 26: None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16: 
None, 18: None, 20: None, 22: None, 24: None, 26: None, 28: None}
{2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: None, 16: 
None, 18: None, 20: None, 22: None, 24: None, 26: None, 28: None, 30: None}
{32: None, 2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 14: 
None, 16: None, 18: None, 20: None, 22: None, 24: None, 26: None, 28: None, 
30: None}
{32: None, 2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 34: 
None, 14: None, 16: None, 18: None, 20: None, 22: None, 24: None, 26: None, 
28: None, 30: None}
{32: None, 2: None, 4: None, 6: None, 8: None, 10: None, 12: None, 34: 
None, 14: None, 16: None, 18: None, 20: None, 22: None, 24: None, 36: None, 
26: None, 28: None, 30: None}
{32: None, 2: None, 4: None, 38: None, 6: None, 8: None, 10: None, 12: 
None, 34: None, 14: None, 16: None, 18: None, 20: None, 22: None, 24: None, 
36: None, 26: None, 28: None, 30: None}

The fact that integers hash to themselves may be unlikely to change, but 
the sizes of the hash tables, or the conflict resolution strategy when an 
insertion hits an already used slot could all vary in other versions of 
Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Issue of redirecting the stdout to both file and screen

2007-05-28 Thread Gabriel Genellina
En Mon, 28 May 2007 06:17:39 -0300, 人言落日是天涯,望极天涯不见家  
<[EMAIL PROTECTED]> escribió:

> I wanna print the log to both the screen and file, so I simulatered a
> 'tee'
>
> class Tee(file):
>
> def __init__(self, name, mode):
> file.__init__(self, name, mode)
> self.stdout = sys.stdout
> sys.stdout = self
>
> def __del__(self):
> sys.stdout = self.stdout
> self.close()
>
> def write(self, data):
> file.write(self, data)
> self.stdout.write(data)
>
> Tee('logfile', 'w')
> print >>sys.stdout, 'abcdefg'
>
> I found that it only output to the file, nothing to screen. Why?
> It seems the 'write' function was not called when I *print* something.

You create a Tee instance and it is immediately garbage collected. I'd  
restore sys.stdout on Tee.close, not __del__ (you forgot to call the  
inherited __del__ method, btw).
Mmm, doesn't work. I think there is an optimization somewhere: if it looks  
like a real file object, it uses the original file write method, not yours.
The trick would be to use an object that does NOT inherit from file:

import sys
class TeeNoFile(object):
 def __init__(self, name, mode):
 self.file = open(name, mode)
 self.stdout = sys.stdout
 sys.stdout = self
 def close(self):
 if self.stdout is not None:
 sys.stdout = self.stdout
 self.stdout = None
 if self.file is not None:
 self.file.close()
 self.file = None
 def write(self, data):
 self.file.write(data)
 self.stdout.write(data)
 def flush(self):
 self.file.flush()
 self.stdout.flush()
 def __del__(self):
 self.close()

tee=TeeNoFile('logfile', 'w')
print 'abcdefg'
print 'another line'
tee.close()
print 'screen only'
del tee # should do nothing

-- 
Gabriel Genellina

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

Formal interfaces with Python

2007-05-28 Thread Florian Lindner
Hello,
some time ago I've heard about proposals to introduce the concecpt of
interfaces into Python. I found this old and rejected PEP about that:
http://www.python.org/dev/peps/pep-0245/

What is the current status of that?

Thanks,

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


Re: speeding things up with C++

2007-05-28 Thread bullockbefriending bard
thanks! i'll look into this.

On May 27, 5:35 am, Che Guevara <[EMAIL PROTECTED]> wrote:
> On May 26, 11:19 am, bullockbefriending bard <[EMAIL PROTECTED]>
> wrote:
>
> > However, I hope someone reading this will be able to tell me that I'm
> > being a total pessimist and that in fact it isn't very difficult to do
> > what I want to do using SWIG. I'm not asking for a complete solution,
> > more like some general pointers from someone who has actually done
> > something similar before.
>
> I do stuff like that with ctypes 
> (http://docs.python.org/lib/module-ctypes.html
> )!
> I'm sure you can figure out some way to pass/return data to/from your C
> ++ lib.
> The easiest way - use strings or arrays, but if you dig deeper into
> ctyles documentation,
> I'm sure you will find a better solution!
>
> Good luck,
> -- misreckoning


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


FTP not Returning (Python on Series 60 Nokia)

2007-05-28 Thread Eisl Thomas
Hi!

Do you already have found a solution for the FTP.storbinary 
hang-up-problem? I am writing a program who connects himself a lot of 
times to a FTP-Server, but in about 1 of 100 cases, it gets stuck in the 
storbinary command although the connection seems to work. I have already 
tried to set a timeout with ftpserver.sock.settimeout(60), but it 
doesn't work either...

Thx for your answer!
Greetz from Austria
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: speeding things up with C++

2007-05-28 Thread bullockbefriending bard
I wonder if Jython might be the answer? Java is going to be faster
than Python for the time-critical part of my program. Does anybody
have experience getting data structures like nested lists / tuples
into a java routine from a running jython program (and then back
again)?

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


pyAntTasks

2007-05-28 Thread kilnhead
I am trying to use pyAntTasks in Eclipse. I have followed the example
in the ibm doc, but I get  the following error:

[taskdef] Could not load definitions from resource
pyAntTasks.properties. It could not be found.

I have added pyAntTasks to my classpath and AntHome directory.

Anybody have any ideas?

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


Re: Issue of redirecting the stdout to both file and screen

2007-05-28 Thread Peter Otten
Gabriel Genellina wrote:

> En Mon, 28 May 2007 06:17:39 -0300, ???
> <[EMAIL PROTECTED]> escribió:
> 
>> I wanna print the log to both the screen and file, so I simulatered a
>> 'tee'
>>
>> class Tee(file):
>>
>> def __init__(self, name, mode):
>> file.__init__(self, name, mode)
>> self.stdout = sys.stdout
>> sys.stdout = self
>>
>> def __del__(self):
>> sys.stdout = self.stdout
>> self.close()
>>
>> def write(self, data):
>> file.write(self, data)
>> self.stdout.write(data)
>>
>> Tee('logfile', 'w')
>> print >>sys.stdout, 'abcdefg'
>>
>> I found that it only output to the file, nothing to screen. Why?
>> It seems the 'write' function was not called when I *print* something.
> 
> You create a Tee instance and it is immediately garbage collected. 

It is not garbage collected until the next assignment to sys.stdout.

Peter

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


Good idea to use a class as function with __new__?

2007-05-28 Thread glomde
Hi,

I am implementing som code generation and want to to use some variant
of the template method pattern.

What I came up with is to have a class with the common part
in a method and the subclasses can then override the Customize methods
to do their own special part.

Now to the question I use the __new__ to return the result instead
of the instance. So that the class is used as an function.

So insted of having.

a = Template()
result = a.__TemplateMethod(preifix="foo")

I can write:

result = Template(prefix="foo")



class Template(object):

   def __init__(cls, *args, **kwds):
  pass

   def __new__(cls, *args, **kwds):
  obj = super(Template, cls).__new__(cls, *args, **kwds)
  return obj.__TemplateMethod(*args, **kwds)

   def Customize1(self, prefix="hello", *args, **kwds):
  return prefix+"1\n"

   def Customize2(self, prefix="hello", *args, **kwds):
  return prefix+"2\n"

   def __TemplateMethod(self, *args, **kwds):
  result = ""
  result += self.Customize1(*args, **kwds)
  result += self.Customize1(*args, **kwds)
  return result


b = Template("foo")

print b

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


Re: Flags of the world

2007-05-28 Thread Ben Finney
Tim Churches <[EMAIL PROTECTED]> writes:

> http://shaheeilyas.com/flags/
>
> Scroll to the bottom to see why this is not entirely off-topic.

I fail to see what it has to do with the thread you're replyiing to,
which is a discussion of creating a dictionary from a list
comprehension.

If you want to start a new thread, compose a new message, not a reply
to an existing thread.

-- 
 \ "If you ever catch on fire, try to avoid seeing yourself in the |
  `\mirror, because I bet that's what REALLY throws you into a |
_o__)  panic."  -- Jack Handey |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is PEP-8 a Code or More of a Guideline?

2007-05-28 Thread John J. Lee
Paul McGuire <[EMAIL PROTECTED]> writes:
[...]
> http://mail.python.org/pipermail/python-dev/2005-December/058750.html
> 
> At first, Guido seemed ambivalent, and commented on the
> contentiousness of the issue, but it seems that the "non-English
> speakers can more easily find word breaks marked with underscores"
> justification tipped the scale in favor of
> lower_case_with_underscores.
[...]

That rationale seems undermined by the frequent use of runtogether
names in the standard library.  These can be confusing even to native
speakers.  And every time you come up with a new name, or try to
remember an old one, you have to decide or remember whether it's
likethis or like_this.

Even as a native English speaker, some of these are tricky --
e.g. urllib has a private class named "addinfourl".  "What's this
'fourl' we're adding in?"

(In fact, the method adds attributes named "info" and "url".  Even
though I've read that name hundreds of times, my brain always insists
on reading it "add in fourl".)

This is the worst of both worlds: inconsistent and hard to understand.


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


Re: What's the best way to iniatilize a function

2007-05-28 Thread Steven D'Aprano
On Mon, 28 May 2007 11:01:26 +0200, Gregor Horvath wrote:

> Jack schrieb:
> 
>> I didn't call del explicitly. I'm expecting Python to call it when
>> the program exits. I put a logging line in __del__() but I never
>> see that line printed. It seems that __del__() is not being called
>> even when the program exits. Any idea why?
>> 
>> 
> 
> http://effbot.org/pyfaq/my-class-defines-del-but-it-is-not-called-when-i-delete-the-object.htm
> 
> better solutions:
> 
> http://docs.python.org/ref/try.html
> http://docs.python.org/whatsnew/pep-343.html


They might be better solutions, but not for the Original Poster's problem. 

The O.P. has a library that has to hang around for long time, not just a
call or two, and then needs to be closed. 

try...except and with define *blocks of code*, not long-lasting libraries
with data, functions, etc. Maybe you could shoe-horn the O.P.'s problem
into a with block, but the result would surely be ugly and fragile.



-- 
Steven.

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


Re: Ancient projectiles (was: Muzzle Velocity (was: High resolution sleep (Linux))

2007-05-28 Thread John J. Lee
Roy Smith <[EMAIL PROTECTED]> writes:

> In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] (Cameron Laird) 
> wrote:
> 
> > Hmmm; now you've got me curious.  What *were* the first
> > composite projectiles?
> 
> Fetchez la Vache!

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


Python-URL! - weekly Python news and links (May 28)

2007-05-28 Thread Gabriel Genellina
QOTW:  "Good God! Is there *anything* that python does not already do? I
hardly feel the need to write programs anymore ...  Its really 80% like
of the questions that are asked here get answered along the lines of:
import some_fancy_module
solution = some_fancy_module.exactly_the_right_function_to_solve(problem)
" - Wildemar Wildenburger

"Whenever you are tempted to create dynamically variables names, 99% of
the time what you really want is a data structure, typically a dict or
a list." - George Sakkis


An example shows how much more convenient it is to use cElementTree
than to write a custom expat parser:
http://mail.python.org/pipermail/python-list/2007-May/441995.html

The Time Machine in action again: How to enumerate classes in a module,
in the same order they were defined:
http://mail.python.org/pipermail/python-list/2007-May/442009.html

str.lower()/upper() may not work as expected even on familiar
encodings like utf-8:
http://mail.python.org/pipermail/python-list/2007-May/442195.html

Steve Holden shows the power of __getattr__, modifying functions
on-the-fly:
http://mail.python.org/pipermail/python-list/2007-May/442432.html

Learning by example: Ten small-but-useful programs increase from
one line to ten lines in length and demonstrate key Python concepts:
http://mail.python.org/pipermail/python-list/2007-May/442529.html
http://wiki.python.org/moin/SimplePrograms

Python cheerleading:
http://opensource.sys-con.com/read/368040.htm  

http://www.devchix.com/2007/05/24/beautiful-python-the-programming-language-that-taught-me-how-to-love-again/

The advantages of using a module as a singleton - let Python do the
hard work:
http://mail.python.org/pipermail/python-list/2007-May/442640.html

Debugging extension modules on Windows may be difficult without the proper
(commercial) compiler. This topic shows how to do that using only freely
available tools:

http://groups.google.de/group/comp.lang.python/browse_thread/thread/e441a581a0d354ab

Think before using inheritance: a Point is not a list:

http://groups.google.de/group/comp.lang.python/browse_thread/thread/0cdfa8c65bf8c195

Michelle Simioniato on decorators again:  functools makes it easy to
decorate methods:
http://mail.python.org/pipermail/python-list/2007-May/442057.html

Tips on how to "sell" yourself as a freelancer:
http://mail.python.org/pipermail/python-list/2007-May/442476.html



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

The Python Papers aims to publish "the efforts of Python enthusiats".
http://pythonpapers.org/

Readers have recommended the "Planet" sites:
http://planetpython.org
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

Steve Bethard continues the marvelous tradition early borne by
Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim
Lesher of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF)

Re: itertools.groupby

2007-05-28 Thread Carsten Haese
On Sun, 2007-05-27 at 18:12 -0700, Steve Howell wrote:
> [...] there is no way
> that "uniquekeys" is a sensible variable [...]

That's because the OP didn't heed the advice from the docs that
"Generally, the iterable needs to already be sorted on the same key
function."

> http://informixdb.blogspot.com/2007/04/power-of-generators-part-two.html
> > 
> 
> Do we now, or could we, link to this example from the
> docs?

Do we? No. Could we? Technically we could, but I'm not sure we should.
The article is about more than just groupby. I just brought it up as one
readily available instance of an independent source of examples.

> To repeat myself, I think a concrete example is
> beneficial even on the main page:

I disagree. Examples add clutter to the page of synopses. Somebody
looking for examples should look on the page that's conveniently called
Examples.

Suppose hypothetically you wanted to show off a really neat example that
involves chain, izip, and groupby. If the examples were forced into the
page of function synopses, you'd have to duplicate it in all three
functions, or randomly pick one function for which your example is an
example. Having a separate examples page that is not arbitrarily
sectioned by function name makes more sense.

Best regards,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: What's the best way to iniatilize a function

2007-05-28 Thread Steven D'Aprano
On Sun, 27 May 2007 23:20:49 -0700, Jack wrote:

> Thanks Steven, for the reply. Very helpful. I've got a lot to learn in 
> Python :)
> 
> Some questions:
> 
>> (1) Python can automatically free most data structures and close open
>> files, but if your needs are more sophisticated, this approach may not be
>> suitable.
> 
> Since it's a wrapper of a DLL or .so file, I actually need to call 
> mylib_exit()
> to do whatever cleanup the library needs to do.

Well, there may be better ways, but I'd do something like this:


# === mylib module ===

# Exception raised if library is not initiated
class Uninitiated(Exception):
pass


def _init():
"""Private set-up code."""
global DATA, _INITIALIZED
DATA = range(10) # or something more useful
_INITIALIZED = True

def _close():
"""Private tear-down code."""
global DATA, _INITIALIZED
del DATA, _INITIALIZED



def isinited():
"""Return True if the library is initialized, otherwise False."""
try:
_INITIALIZED; return True
except NameError:
return False



def init():
"""Public set-up code."""
if not isinited():  _init()

def close():
"""Public tear-down code."""
if isinited():  _close()

exit = close  # alias for exit/close.


def func():
if isinited():
return DATA[0]
else:
raise Uninitiated("Library is not initialized")


All of the above can be modified to be in a class instead of a module.
That's especially useful if you can have multiple instances, perhaps with
different state.


 
>>> 2. what's the right way to call mylib_exit()? I put it in __del__(self)
>>> but it is not being called in my simple test.
>>
>> instance.__del__ is only called when there are no references to the
>> instance.
> 
> I didn't call del explicitly. I'm expecting Python to call it when
> the program exits. I put a logging line in __del__() but I never
> see that line printed. It seems that __del__() is not being called
> even when the program exits. Any idea why?

Python tries really really hard to call instance.__del__() but there are
pathological cases where it just can't. Maybe you've found one of them. 

But I'm guessing that you may have defined a __del__ method, but not
actually created an instance. If so, __del__ will never be called.

This should work:

class Foo(object):
def __del__(self):
print "All gone now"

instance = Foo()


When you exit, instance will be garbage collected and instance.__del__()
will be called. But without the instance, __del__ is not called on the
class directly.


Hope this was some help,


-- 
Steven.

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


Re: What's the best way to iniatilize a function

2007-05-28 Thread Laurent Pointal
Jack wrote:

>>> 2. what's the right way to call mylib_exit()? I put it in __del__(self)
>>> but it is not being called in my simple test.
>>
>> instance.__del__ is only called when there are no references to the
>> instance.
> 
> I didn't call del explicitly. I'm expecting Python to call it when
> the program exits. I put a logging line in __del__() but I never
> see that line printed. It seems that __del__() is not being called
> even when the program exits. Any idea why?

If you make your extension available as a module (Python or C), you can use
atexit: http://docs.python.org/lib/module-atexit.html

Note: your exit handler will only be called at normal termination.

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


Re: Error in optparse documentation

2007-05-28 Thread Shatadal
On May 28, 2:19 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> In <[EMAIL PROTECTED]>, Shatadal
> wrote:
>
> > I think the documentation should be modified so that it is made clear
> > that %default in the help string behaves as is claimed only in version
> > 2.4 and higher.
>
> Maybe something should be added for clarity but I don't think it's an
> error in the docs.  You are reading documentation for Python 2.5 and
> expect everything in it to work in older versions too?
>
> Pick the right documentation fromhttp://www.python.org/doc/versions/

Thanks Marc. I did not know that documentation for previous versions
existed.

>
> Ciao,
> Marc 'BlackJack' Rintsch


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


Re: Newbie question - better way to do this?

2007-05-28 Thread Steve Howell

--- Nis Jørgensen <[EMAIL PROTECTED]> wrote:

> Steve Howell skrev:
> 
> > def firstIsCapitalized(word):
> > return 'A' <= word[0] <= 'Z'
> 
> For someone who is worried about the impact of
> non-ascii identifiers,
> you are making surprising assumptions about the
> contents of data.
> 

The function there, which I don't even remotely
defend, had nothing to with the main point of the
thread.  Others pointed out that correct idiom here is
word.istitle(), but the main point of the thread was
how to prevent the newbie from essentially reinventing
itertools.groupby.

If you want to point out holes in my logic about the
impact of non-ascii identifiers (the above code,
though bad, does not suggest a hole in my logic; it
perhaps even adds to my case), can you kindly do it in
a thread where that's the main point of the
discussion?




   
Sick
 sense of humor? Visit Yahoo! TV's 
Comedy with an Edge to see what's on, when. 
http://tv.yahoo.com/collections/222
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: itertools.groupby

2007-05-28 Thread Carsten Haese
On Sun, 2007-05-27 at 20:28 -0700, Paul Rubin wrote:
>fst = operator.itemgetter(0)
>snd = operator.itemgetter(1)
> 
>def bates(fd):
>  # generate tuples (n,d) of lines from file fd,
>  # where n is the record number.  Just iterate through all lines
>  # of the file, stamping a number on each one as it goes by.
>  n = 0   # record number
>  for d in fd:
> if d.startswith('New Record'): n += 1
> yield (n, d)
> 
>def records(fd):
>   for i,d in groupby(bates(fd), fst):
>  yield imap(snd, d)

Now there's a clever variation of the Schwartzian transform: decorate,
groupby, undecorate.

That's a nice example of groupby, but it could benefit from using better
variable names.

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Can string be callable as a method ?

2007-05-28 Thread Jia Lu
Hi all
 I tried to scan a directory and __import__ all modules ,

imported module: help
imported module: __init__
imported module: hi
imported module: thanks

and I scaned all methods in them, and put them to a list like:

[['f_chelp', 'f_help'], [], ['f_exclaim', 'f_hi', 'random'],
['f_thanks', 'random']]

But how can I call them from that list??

Thank you.

Jia Lu

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


Re: a bug in python windows service?

2007-05-28 Thread momobear
On May 27, 11:25 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Sun, 27 May 2007 09:07:36 -0300, momobear <[EMAIL PROTECTED]> escribió:
>
> >> Instead of extending join(), write a specific method to signal the
> >> quitEvent or just let the caller signal it. And I don't see in this
> >> example why do you need two different events (one on the thread, another
> >> on the service controller), a single event would suffice.
>
> > I don't think a single event is enought, since I think the event
> > python created and windows event are not same kind of event.
>
> They are not the same object, of course (altough the threading.Event
> object relies eventually on a mutex implemented using CreateEvent). But in
> this case both can be successfully used; of course, having the Python
> object a more "pythonic" interfase (not a surprise!), it's easier to use.
> The same example modified using only a threading.Event object (and a few
> messages to verify how it runs):
>
> import threading
>  from win32api import OutputDebugString as ODS
>
> class workingthread(threading.Thread):
>  def __init__(self, quitEvent):
>  self.quitEvent = quitEvent
>  self.waitTime = 1
>  threading.Thread.__init__(self)
>
>  def run(self):
>  while not self.quitEvent.isSet():
>  ODS("Running...\n")
>  self.quitEvent.wait(self.waitTime)
>  ODS("Exit run.\n")
>
> import win32serviceutil
> import win32event
>
> class testTime(win32serviceutil.ServiceFramework):
>  _svc_name_ = "testTime"
>  _svc_display_name_ = "testTime"
>  _svc_deps_ = ["EventLog"]
>
>  def __init__(self, args):
>  win32serviceutil.ServiceFramework.__init__(self, args)
>  self.hWaitStop = threading.Event()
>  self.thread = workingthread(self.hWaitStop)
>
>  def SvcStop(self):
>  self.hWaitStop.set()
>
>  def SvcDoRun(self):
>  self.thread.start()
>  self.hWaitStop.wait()
>  self.thread.join()
>
> if __name__ == '__main__':
>  win32serviceutil.HandleCommandLine(testTime)
>
> --
> Gabriel Genellina

Great! thanks, now I understand the real work of the python windows
service.

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


Re: gui application on cross platform

2007-05-28 Thread johnf
james_027 wrote:

> Hi,
> 
> I am using delphi to develop gui application, and wish to make a shift
> to python. here are some of my question/concern...
> 
> 1. is python develop gui application a cross platform? just like java
> swing?
> 2. delphi makes things easy for me like coding for a specific event on
> a specific component, could it be the same for python?
> 3. are there cool library of component like in delphi available for
> python that will make database application more usesable?
> 4. where do I start the learning curve? I did some research and I
> don't know which one to take among wxwdiget, pygtk, and etc.
> 
> 
> Thanks
> james
May I suggest you take a close look at Dabo (www.dabodev.com).  Dabo was
designed from the ground up to do exact what you are asking for.  Take a
look at the Dabo screencast
(http://leafe.com/screencasts/dataenvironment1.html)
which will provide an easy review of most of what Dabo can do.  

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


Re: Is PEP-8 a Code or More of a Guideline?

2007-05-28 Thread Steven Bethard
John J. Lee wrote:
> Paul McGuire <[EMAIL PROTECTED]> writes:
> [...]
>> http://mail.python.org/pipermail/python-dev/2005-December/058750.html
>>
>> At first, Guido seemed ambivalent, and commented on the
>> contentiousness of the issue, but it seems that the "non-English
>> speakers can more easily find word breaks marked with underscores"
>> justification tipped the scale in favor of
>> lower_case_with_underscores.
> [...]
> 
> That rationale seems undermined by the frequent use of runtogether
> names in the standard library.  These can be confusing even to native
> speakers.  And every time you come up with a new name, or try to
> remember an old one, you have to decide or remember whether it's
> likethis or like_this.
> 
> Even as a native English speaker, some of these are tricky --
> e.g. urllib has a private class named "addinfourl".  "What's this
> 'fourl' we're adding in?"
> 
> (In fact, the method adds attributes named "info" and "url".  Even
> though I've read that name hundreds of times, my brain always insists
> on reading it "add in fourl".)
> 
> This is the worst of both worlds: inconsistent and hard to understand.

Sounds like a good candidate for a rename in Python 3000.

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


Re: Can string be callable as a method ?

2007-05-28 Thread Steven D'Aprano
On Mon, 28 May 2007 06:45:47 -0700, Jia Lu wrote:

> Hi all
>  I tried to scan a directory and __import__ all modules ,
> 
> imported module: help
> imported module: __init__
> imported module: hi
> imported module: thanks
> 
> and I scaned all methods in them, and put them to a list like:
> 
> [['f_chelp', 'f_help'], [], ['f_exclaim', 'f_hi', 'random'],
> ['f_thanks', 'random']]
> 
> But how can I call them from that list??


>>> import math
>>> dir(math)
['__doc__', '__file__', '__name__', 'acos', 'asin', ... ]
>>> 
>>> math.__dict__['acos'](0)
1.5707963267948966
>>> getattr(math, 'asin')(0)
0.0

Instead of storing the names of the functions, better to store the
functions themselves:

>>> my_list = [math.acos, math.asin]
>>> my_list[0](1)
0.0


Hope this helps,


-- 
Steven.

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


Re: itertools.groupby

2007-05-28 Thread Steve Howell

--- Raymond Hettinger <[EMAIL PROTECTED]> wrote:

> +  The operation of \function{groupby()} is similar
> to the \code{uniq}
> filter
> +  in \UNIX{}.  [...]

Thanks!

The comparison of groupby() to "uniq" really clicks
with me.  

To the extent that others like the Unix command line
analogy for understanding Python idioms, I compiled
the following list, which includes a couple groupby
examples from Raymond.


>>> 'abacadabra'[:5] # head -5
abaca

>>> 'abacadabra'[-5:] # tail -5
dabra

>>> [word for word in 'aaa,abc,foo,zzz,cba'.split(',')
if 'a' in word] # grep a
['aaa', 'abc', 'cba']

>>> sorted('abracadabra')   # sort
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r',
'r']

>>> list(reversed(sorted('abracadabra')))   # sort -r
['r', 'r', 'd', 'c', 'b', 'b', 'a', 'a', 'a', 'a',
'a']

>>> [k for k, g in groupby(sorted('abracadabra'))]   #
sort | uniq
['a', 'b', 'c', 'd', 'r']

>>> [(k, len(list(g))) for k, g in
groupby(sorted('abracadabra'))]   # sort | uniq -c
[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]

>>> [k for k, g in groupby(sorted('abracadabra')) if
len(list(g)) > 1] # sort | uniq -d
['a', 'b', 'r']


   
Get
 the Yahoo! toolbar and be alerted to new email wherever you're surfing.
http://new.toolbar.yahoo.com/toolbar/features/mail/index.php
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is PEP-8 a Code or More of a Guideline?

2007-05-28 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Steven Bethard <[EMAIL PROTECTED]> wrote:

> Stefan Sonnenberg-Carstens wrote:
> > Paul McGuire schrieb:
> >> I'm starting a new thread for this topic, so as not to hijack the one
> >> started by Steve Howell's excellent post titled "ten small Python
> >> programs".
> >>
> >> In that thread, there was a suggestion that these examples should
> >> conform to PEP-8's style recommendations, including use of
> >> lower_case_with_underscores style for function names.  I raised some
> >> questions about this suggestion, since I liked the names the way they
> >> were, but as a result, part of the discussion has drifted into a
> >> separate track about PEP-8, and naming styles.
> >
> > I prefer mixedCaseStyle, and I think that should be "standard", as this 
> > style is commonly
> > used in all "major" languages , for example Java,C++,C#.
> > It shortens the identifiers but leaves the meaning intact.
> 
> The argument for under_score_names is usually that non-native speakers 
> can more easily find the word boundaries. Not being a non-native speaker 
> ;-) I can't verify that one, but it's pretty plausible given the current 
> amount of money spent on research on automatic word-segmentation for 
> languages like Chinese. =)
> 
> STeVe

I've gone through a few different flavors of composite name schemes over 
the years (starting with FORTRAN's 6 upper case character limit).  When 
first exposed to camelCase, I thought it was horrible.  Eventually, I came 
to like it.

On the other hand, I'm convinced that words_with_underscores, is easier to 
read.  This is especially true when abbreviations creep into variable 
names.  It's certainly easier to parse ip_address as compared to IPAddress.  
Same with snmp_manager vs SNMPManager.

I really like lisp's convention of using dashes instead of underscores, 
i.e. ip-address and snmp-manager.  I think the only reason most languages 
don't use that is the parsing ambiguity, but if you required white space 
around all operators, then "ip-address" would unambiguously be a variable 
name and "ip - address" would be a subtraction expression.
-- 
http://mail.python.org/mailman/listinfo/python-list


gettext backwards

2007-05-28 Thread SPE - Stani's Python Editor
I am developping an international application for which I use gettext.
An user can fill in certain fields with variable names which are also
localized, eg: filename

_('filename') = 'bestandsnaam' #for dutch

As an english user might save this configuration, I want that eg a
Dutch user can open this configuration but see 'filename' in Dutch
('bestandsnaam'). So my question is, does gettext supports reverse
translation (assuming all translation strings are unique)? The reverse
function would take a translated string and put it back in the
original:

foo('bestandsnaam') = 'filename' #to allow an english user to work
with a file saved by a dutch user

Of course I can customize _() so it keeps track of the translations in
a reverse dictionary or I could build an external reverse dictionary,
but I was wondering if there was a more elegant solution.

Stani
--
http://www.stani.be
http://pythonide.stani.be




In my code this would be called like

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


Re: itertools.groupby

2007-05-28 Thread Steve Howell

--- Paul Rubin <"http://phr.cx"@NOSPAM.invalid> wrote:
> [...]
> Here's yet another example that came up in something
> I was working on:
> you are indexing a book and you want to print a list
> of page numbers
> for pages that refer to George Washington.  If
> Washington occurs on
> several consecutive pages you want to print those
> numbers as a 
> hyphenated range, e.g.
> 
>Washington, George: 5, 19, 37-45, 82-91, 103
> 
> This is easy with groupby (this version not tested
> but it's pretty close
> to what I wrote in the real program).  Again it
> works by Bates numbering,
> but a little more subtly (enumerate generates the
> Bates numbers):
> 
>snd = operator.itemgetter(1)   # as before
> 
>def page_ranges():
>   pages = sorted(filter(contains_washington,
> all_page_numbers))
>   for d,g in groupby(enumerate(pages), lambda
> (i,p): i-p):
> h = map(snd, g)
> if len(h) > 1:
>yield '%d-%d'% (h[0], h[-1])
> else:
>yield '%d'% h[0]
>print ', '.join(page_ranges())
>
> [...]

Cool.

Here's another variation on itertools.groupby, which
wraps text from paragraphs:

import itertools
lines = [line.strip() for line in '''
This is the
first paragraph.

This is the second.
'''.split('\n')]

for has_chars, frags in itertools.groupby(lines,
lambda x: len(x) > 0):
if has_chars:
print ' '.join(list(frags))
# prints this:
#
# This is the first paragraph.
# This is the second.


I put the above example here:

http://wiki.python.org/moin/SimplePrograms




  

Park yourself in front of a world of choices in alternative vehicles. Visit the 
Yahoo! Auto Green Center.
http://autos.yahoo.com/green_center/ 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question - better way to do this?

2007-05-28 Thread Nis Jørgensen
Steve Howell skrev:
> --- Nis Jørgensen <[EMAIL PROTECTED]> wrote:
> 
>> Steve Howell skrev:
>>
>>> def firstIsCapitalized(word):
>>> return 'A' <= word[0] <= 'Z'
>> For someone who is worried about the impact of
>> non-ascii identifiers,
>> you are making surprising assumptions about the
>> contents of data.
>>
> 
> The function there, which I don't even remotely
> defend, had nothing to with the main point of the
> thread.  Others pointed out that correct idiom here is
> word.istitle(), but the main point of the thread was
> how to prevent the newbie from essentially reinventing
> itertools.groupby.

The subject line says "Newbie question - better way to do this". I was
hinting at a better  way to do what you did, which was supposedly a
better way of doing what the newbie wanted.

I disagree that word.istitle is the correct idiom - from the naming of
the function in the original example, I would guess "word[0].isupper"
would do the trick.

> If you want to point out holes in my logic about the
> impact of non-ascii identifiers (the above code,
> though bad, does not suggest a hole in my logic; it
> perhaps even adds to my case), can you kindly do it in
> a thread where that's the main point of the
> discussion?

Will do.

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


Re: Is PEP-8 a Code or More of a Guideline?

2007-05-28 Thread Steve Howell

--- Roy Smith <[EMAIL PROTECTED]> wrote:
> It's certainly easier to parse ip_address as
> compared to IPAddress.  
> Same with snmp_manager vs SNMPManager.
> 

Somebody earlier was actually advocating something
called proper_case, in which you can capitalize
certain letters for clarity,  like
test_for_Heisenberg_uncertainty.

Regarding acronyms, I'm curious about how people
interpret PEP 8 for the following.

Acronyms:

   get_HTTP_response
   get_http_response

Abbreviations:

   get_file_id
   get_file_ID






   
Be
 a better Globetrotter. Get better travel answers from someone who knows. 
Yahoo! Answers - Check it out.
http://answers.yahoo.com/dir/?link=list&sid=396545469
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: itertools.groupby

2007-05-28 Thread 7stud
On May 27, 6:50 pm, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
> On May 27, 2:59 pm, Steve Howell <[EMAIL PROTECTED]> wrote:
>
> > These docs need work.  Please do not defend them;
> > please suggest improvements.
>
> FWIW, I wrote those docs.  Suggested improvements are
> welcome; however, I think they already meet a somewhat
> high standard of quality:
>
> - there is an accurate, succinct one-paragraph description
>   of what the itertool does.
>
> - there is advice to pre-sort the data using the same
>   key function.
>
> - it also advises when to list-out the group iterator
>   and gives an example with working code.
>
> - it includes a pure python equivalent which shows precisely
>   how the function operates.
>
> - there are two more examples on the next page.  those two
>   examples also give sample inputs and outputs.
>
> This is most complex itertool in the module.  I believe
> the docs for it can be usable, complete, and precise,
> but not idiot-proof.
>
> The groupby itertool came-out in Py2.4 and has had remarkable
> success (people seem to get what it does and like using it, and
> there have been no bug reports or reports of usability problems).
> All in all, that ain't bad (for what 7stud calls a poster child).
>
> Raymond



>- there is an accurate, succinct one-paragraph description
>  of what the itertool does.

As is often the case, the specifics of the description may only be
meaningful to someone who already knows what groupby does.  There are
many terms and concepts that experienced programmers use to describe
programming problems, but often the terms and concepts only ring true
with people who already understand the problem, and they are not at
all helpful for someone who is trying to learn about the concept.

Sometimes when you describe a function accurately, the description
becomes almost impossible to read because of all the detail.  What is
really needed is a general, simple description of the primary use of
the function, so that a reader can immediately employ the function in
a basic way.  Code snippets are extremely helpful in that regard.
Subsequently, the details and edge cases can be fleshed out in the
rest of the description.

>- there is advice to pre-sort the data using the same
>  key function.

But you have to know why that is relevant in the first place--
otherwise it is just a confusing detail.  Two short code examples
could flesh out the relevance of that comment.  I think I now
understand why pre-sorting is necessary: groupby only groups similar
items that are adjacent to each other in the sequence, and similar
items that are elsewhere in the sequence will be in a different group.

>- it includes a pure python equivalent which shows precisely
>  how the function operates.

It's too complicated.  Once again, it's probably most useful to an
experienced programmer who is trying to figure out some edge case. So
the code example is certainly valuable to one group of readers--just
not a reader who is trying to get a basic idea of what groupby does.

>- there are two more examples on the next page.  those two
>  examples also give sample inputs and outputs.

I didn't see those.

> people seem to get what it does and like
> using it, and
> there have been no bug reports or reports of
> usability problems

Wouldn't you get the same results if not many people used groupby
because they couldn't understand what it does?

I don't think you even need good docs if you allow users to attach
comments to the docs because all the issues will get fleshed out by
the users.  I appreciate the fact that it must be difficult to write
the docs--that's why I think user comments can help.

How about this for the beginning of the description of groupby in the
docs:

groupby divides a sequence into groups of similar elements.

Compare to:

> Make an iterator that returns consecutive keys and groups
> from the iterable.

Huh?

Continuing with a kinder, gentler description:

With a starting sequence like this:

lst = [1, 2, 2, 2, 1, 1, 3]

groupby divides the sequence into groups like this:

[1], [2, 2, 2], [1, 1], [3]

groupby takes similar elements that are adjacent to each other and
gathers them into a group.  If you sort the sequence beforehand, then
all the similar elements in a sequence will be adjacent to one
another, and therefore they will all end up in one group.

Optionally, you can specify a function func which groupby will use to
determine which elements in the sequence are similar (if func isn't
specified or is None, then func defaults to the identity function
which returns the element unchanged). An example:

--
import itertools

lst = [1, 2, 2, 2, 1, 1, 3]

def func(num):
if num == 2:
return "a"
else:
return "b"

keys = []
groups = []
for k, g in itertools.groupby(lst, func):
keys.append(k)
groups.append( list(g) )

print keys
print groups

---output:---
['b', 'a', 'b']
[[1], [2, 2, 2], [1, 1, 3]]

When func is applied to an element in the list,

Re: ten small Python programs

2007-05-28 Thread Stef Mientki
Steve Howell wrote:
> I've always thought that the best way to introduce new
> programmers to Python is to show them small code
> examples.  
> 
This is really a nice piece of missing Python.

Sorry I didn't follow this thread accurately,
but have you considered to produce an example environment like in wxPython ?

The wxPython demo program is written as an interactive tutorial,
with a few hundred examples, nicely ordered in groups.
The user can view the demo, the code and the help text.
The user can also change the code and see the results right away.

It would even be nicer, if everybody could drop her/his examples
in a standard way, so they would be automatically incorporated in
something like the wxPython interactive demo.

cheers,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ten small Python programs

2007-05-28 Thread Kay Schluehr
Just for the amusement of the audience. The following is a reusable
testscript:

>>> def add_money(amounts):
... pennies = sum([round(int(amount * 100)) for amount in amounts])
... return float(pennies / 100.0)
...
>>> add_money([0.13, 0.02]) == 0.15
0.14999
>>> add_money([0.13, 0.02]) == 0.15
True
>>> assert add_money([0.13, 0.02]) == 0.15
>>> assert add_money([100.01, 99.99]) ==  200
>>> assert add_money([0, -13.00, 13.00]) ==  0


It's just a matter of perspective...

http://fiber-space.de/EasyExtend/doc/consoletest/consoletest.html

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


Re: Issue of redirecting the stdout to both file and screen

2007-05-28 Thread Gabriel Genellina
En Mon, 28 May 2007 09:10:40 -0300, Peter Otten <[EMAIL PROTECTED]>  
escribió:

> Gabriel Genellina wrote:
>
>> En Mon, 28 May 2007 06:17:39 -0300, ???
>> <[EMAIL PROTECTED]> escribió:
>>
>>> def __init__(self, name, mode):
>>> file.__init__(self, name, mode)
>>> self.stdout = sys.stdout
>>> sys.stdout = self
>>>
>>> Tee('logfile', 'w')
>>> print >>sys.stdout, 'abcdefg'
>>>
>>> I found that it only output to the file, nothing to screen. Why?
>>> It seems the 'write' function was not called when I *print* something.
>>
>> You create a Tee instance and it is immediately garbage collected.
>
> It is not garbage collected until the next assignment to sys.stdout.

Yes, sorry, this was my first guess. Later I discovered the real reason  
-you pointed it too-, I should have removed the whole first paragraph on  
my reply.

-- 
Gabriel Genellina

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


Re: Newbie question - better way to do this?

2007-05-28 Thread Steve Howell

--- Nis Jørgensen <[EMAIL PROTECTED]> wrote:

> 
> I disagree that word.istitle is the correct idiom -
> from the naming of
> the function in the original example, I would guess
> "word[0].isupper"
> would do the trick.
> 


That would return something like this:

   

You want to add parens:

word[0].isupper()






   
Luggage?
 GPS? Comic books? 
Check out fitting gifts for grads at Yahoo! Search
http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is PEP-8 a Code or More of a Guideline?

2007-05-28 Thread Sergei Organov
Roy Smith <[EMAIL PROTECTED]> writes:
[...]
> On the other hand, I'm convinced that words_with_underscores, is easier to 
> read.  This is especially true when abbreviations creep into variable 
> names.  It's certainly easier to parse ip_address as compared to IPAddress.  
> Same with snmp_manager vs SNMPManager.

Well, you don't capitalize abbreviations like that in a classic
CamelCase, I believe. Those names ought to be SnmpManager and
IpAddress. Though there is still problem with digits, e.g., Crc24Accum.

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


Re: speeding things up with C++

2007-05-28 Thread Kay Schluehr
On May 26, 11:19 am, bullockbefriending bard <[EMAIL PROTECTED]>
wrote:
> I've done all the requisite profiling and thought fairly deeply about
> the efficiency of my python code, but am still going to have to speed
> up the innermost guts of what I am doing.
>
> Essentially, I need to pass a list of 6-tuples containing only
> integers to my new sadly necessary super-fast compiled language
> function which i am not looking forward to writing:
>
> input: [(1,2,3,4,5,6), (7,8,9,10,11,12),...]
>
> and after much thrashing of processor resources, return data which
> looks like this to the Python calling environment:
>
> output: [( (1, 2), (1,), (12,), (13), (1, 7, 11), (9,) ), (  another
> nested tuple like preceding one  ),  ]
>
> Each member of the returned list is a tuple containing 6 tuples, and
> each of those 6 tuples has at least one integer member. It would also
> be acceptable for the return values to be entirely nested lists
> instead of having the two innermost sequence types as tuples.
>
> I probably want to be using something like C++ because i'm going to
> need to use STL vectors and sets for what i'm doing in the algorithm
> i'm trying to speed up. IIRC Boost tuple is a bit painful for more
> than 10 elements + isn't really essential that I use a a non-mutable
> data type in what will be a small encapsulated bit of a much larger
> system.
>
> Anyway, I can probably very quickly figure out some hacked way to get
> the data into my function given that in the worst case I could take
> advantage of the knowledge that each input tuple always has 6
> elements, and simply pass in a big array of ints. Yes, I know this is
> a bit retarded, but I'm talking worst case assuming on very tight
> schedule and no time to delve deeply into SWIG or whatever. Similarly
> it wouldn't be too difficult to return the result as the mother all of
> all strings which i could then parse fairly easily.
>
> However, I hope someone reading this will be able to tell me that I'm
> being a total pessimist and that in fact it isn't very difficult to do
> what I want to do using SWIG. I'm not asking for a complete solution,
> more like some general pointers from someone who has actually done
> something similar before.
>
> As an added bonus, I wouldn't if this is 'easily' doable using Ocaml
> as the guts instead of C++, I'd be happy to know about it.

A just too obvious recommendation is to drop C++ and use D together
with the Pyd/celerid bridge. Yeah, it sounds a little esoteric but D
is really the Python among the statically typed imperative languages.

http://www.digitalmars.com/d/
http://pyd.dsource.org/index.html


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


Re: Good idea to use a class as function with __new__?

2007-05-28 Thread Gabriel Genellina
En Mon, 28 May 2007 09:17:30 -0300, glomde <[EMAIL PROTECTED]> escribió:

> I am implementing som code generation and want to to use some variant
> of the template method pattern.
>
> What I came up with is to have a class with the common part
> in a method and the subclasses can then override the Customize methods
> to do their own special part.
>
> Now to the question I use the __new__ to return the result instead
> of the instance. So that the class is used as an function.

It works, and I don't see any big problems, but I don't *like* that.
I'd use __call__ instead; that is, write __new__ and __init__ normally -if  
you need them at all- and move the magic to __call__:

 def __call__(self, *args, **kwds):
return self.__TemplateMethod(*args, **kwds)

x = Template()(prefix="foo")
or perhaps:
x = Template(prefix="foo")()

I think the extra () improves readability - it's clear that x comes from a  
function call, it's not a Template instance as one would expect from your  
original code.
And depending on the application, you could keep the instances and call  
them with different arguments - with the original code you always create a  
new instance just to discard it immediately.

-- 
Gabriel Genellina

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


Re: ten small Python programs

2007-05-28 Thread Steve Howell

--- Stef Mientki <[EMAIL PROTECTED]>
wrote:

> Steve Howell wrote:
> > I've always thought that the best way to introduce
> new
> > programmers to Python is to show them small code
> > examples.  
> > 
> This is really a nice piece of missing Python.
>

Thanks.
 

> The wxPython demo program is written as an
> interactive tutorial,
> with a few hundred examples, nicely ordered in
> groups.
> The user can view the demo, the code and the help
> text.
> The user can also change the code and see the
> results right away.
> 

Do you have a link?

> It would even be nicer, if everybody could drop
> her/his examples
> in a standard way, so they would be automatically
> incorporated in
> something like the wxPython interactive demo.
> 

Can you elaborate?





 

8:00? 8:25? 8:40? Find a flick in no time 
with the Yahoo! Search movie showtime shortcut.
http://tools.search.yahoo.com/shortcuts/#news
-- 
http://mail.python.org/mailman/listinfo/python-list


vte examples and installation

2007-05-28 Thread Fabian Braennstroem
Hi,

I am looking for simple vte examples mainly for pygtk.
Can anyone point me in the right direction or is there a better
terminal emulation for pygtk? It would be nice, if there exist a
good howto for installing vte up for the use of python; esp. for an
old redhat/scientific linux machine... I am a little bit confused!?

Greetings!
Fabian

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


Re: Good idea to use a class as function with __new__?

2007-05-28 Thread glomde

Gabriel Genellina wrote:

>  def __call__(self, *args, **kwds):
> return self.__TemplateMethod(*args, **kwds)
>
> x = Template()(prefix="foo")
> or perhaps:
> x = Template(prefix="foo")()
>
> I think the extra () improves readability - it's clear that x comes from a
> function call, it's not a Template instance as one would expect from your
> original code.
> And depending on the application, you could keep the instances and call
> them with different arguments - with the original code you always create a
> new instance just to discard it immediately.
>
> --
Thanks for the reply. I was considering __call__ but in my case it is
really something
that will be discarded immediately. And right now it is is implemented
as function
where I have arguments to send in which customize functions something
like:

def Template(self, func1=Customize1, func2= Customize2, *args,
**kwds):
func1(*args, **kwds)
func2(*args, **kwds)

So I just wanted to organize it a little bit nicer and be able to
subclass instead of
sending in function pointers. But that had the same interface.

But you are right the extra () does make it clearer, so I probably go
for that.

Cheers,

/T

> Gabriel Genellina

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


Build problems with sqlite on OSX

2007-05-28 Thread Darrin Thompson
I'm attempting to build python 2.5.1 fat binaries on OSX and
statically link to a newer sqlite than what ships with OSX. (3.3.17).

I'm getting "Bus Error" early when I run my app. If I turn on a lot of
malloc debugging options and run under gdb I get this trace:

(gdb) info threads
* 1 process 18968 local thread 0x1003  0x900e41d1 in strtol_l ()
(gdb) bt
#0  0x900e41d1 in strtol_l ()
#1  0x900160a5 in atoi ()
#2  0x9406fd80 in sqlite3InitCallback ()
#3  0x0381faf2 in sqlite3_exec (db=0x338d080, zSql=0x331f1e0 "SELECT
name, rootpage, sql FROM 'main'.sqlite_master WHERE
tbl_name='sqlite_sequence'", xCallback=0x9406fd00
, pArg=0xbfffde14, pzErrMsg=0x0) at
./src/legacy.c:93
#4  0x0384c769 in sqlite3VdbeExec (p=0x1945200) at ./src/vdbe.c:4090
#5  0x03816686 in sqlite3Step (p=0x1945200) at ./src/vdbeapi.c:236
#6  0x03816817 in sqlite3_step (pStmt=0x1945200) at ./src/vdbeapi.c:289
#7  0x0380b9aa in _sqlite_step_with_busyhandler (statement=0x1945200,
connection=0x32a77a0) at
/Users/pandora/build-toolchain/build/Python-2.5.1/Modules/_sqlite/util.c:33
#8  0x0380850d in cursor_executescript (self=0x32bd4d0,
args=0x32a2d10) at
/Users/pandora/build-toolchain/build/Python-2.5.1/Modules/_sqlite/cursor.c:788
#9  0x0020e6fc in PyObject_Call (func=0x329ecd8, arg=0x32a2d10,
kw=0x0) at Objects/abstract.c:1860
#10 0x00292a36 in PyEval_CallObjectWithKeywords (func=0x329ecd8,
arg=0x32a2d10, kw=0x0) at Python/ceval.c:3433
#11 0x0020e6cd in PyObject_CallObject (o=0x329ecd8, a=0x32a2d10) at
Objects/abstract.c:1851
#12 0x03806e1c in connection_executescript (self=0x32a77a0,
args=0x32a2d10, kwargs=0x0) at
/Users/pandora/build-toolchain/build/Python-2.5.1/Modules/_sqlite/connection.c:1001
#13 0x002998ae in PyEval_EvalFrameEx (f=0x338c250, throwflag=0) at
Python/ceval.c:3564

Can someone advise as to the correct configure arguments for sqlite or
something else I might be missing?

Thanks in advance.

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


Re: Formal interfaces with Python

2007-05-28 Thread Terry Reedy

"Florian Lindner" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Hello,
| some time ago I've heard about proposals to introduce the concecpt of
| interfaces into Python. I found this old and rejected PEP about that:
| http://www.python.org/dev/peps/pep-0245/
|
| What is the current status of that?

Check
http://www.python.org/dev/peps/pep-3119/
Related are
http://www.python.org/dev/peps/pep-3124/
http://www.python.org/dev/peps/pep-3141/



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


Re: speeding things up with C++

2007-05-28 Thread bullockbefriending bard
thanks. i'll definitely look into this.

On May 28, 10:48 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote:
> On May 26, 11:19 am, bullockbefriending bard <[EMAIL PROTECTED]>
> wrote:
>
>
>
> > I've done all the requisite profiling and thought fairly deeply about
> > the efficiency of my python code, but am still going to have to speed
> > up the innermost guts of what I am doing.
>
> > Essentially, I need to pass a list of 6-tuples containing only
> > integers to my new sadly necessary super-fast compiled language
> > function which i am not looking forward to writing:
>
> > input: [(1,2,3,4,5,6), (7,8,9,10,11,12),...]
>
> > and after much thrashing of processor resources, return data which
> > looks like this to the Python calling environment:
>
> > output: [( (1, 2), (1,), (12,), (13), (1, 7, 11), (9,) ), (  another
> > nested tuple like preceding one  ),  ]
>
> > Each member of the returned list is a tuple containing 6 tuples, and
> > each of those 6 tuples has at least one integer member. It would also
> > be acceptable for the return values to be entirely nested lists
> > instead of having the two innermost sequence types as tuples.
>
> > I probably want to be using something like C++ because i'm going to
> > need to use STL vectors and sets for what i'm doing in the algorithm
> > i'm trying to speed up. IIRC Boost tuple is a bit painful for more
> > than 10 elements + isn't really essential that I use a a non-mutable
> > data type in what will be a small encapsulated bit of a much larger
> > system.
>
> > Anyway, I can probably very quickly figure out some hacked way to get
> > the data into my function given that in the worst case I could take
> > advantage of the knowledge that each input tuple always has 6
> > elements, and simply pass in a big array of ints. Yes, I know this is
> > a bit retarded, but I'm talking worst case assuming on very tight
> > schedule and no time to delve deeply into SWIG or whatever. Similarly
> > it wouldn't be too difficult to return the result as the mother all of
> > all strings which i could then parse fairly easily.
>
> > However, I hope someone reading this will be able to tell me that I'm
> > being a total pessimist and that in fact it isn't very difficult to do
> > what I want to do using SWIG. I'm not asking for a complete solution,
> > more like some general pointers from someone who has actually done
> > something similar before.
>
> > As an added bonus, I wouldn't if this is 'easily' doable using Ocaml
> > as the guts instead of C++, I'd be happy to know about it.
>
> A just too obvious recommendation is to drop C++ and use D together
> with the Pyd/celerid bridge. Yeah, it sounds a little esoteric but D
> is really the Python among the statically typed imperative languages.
>
> http://www.digitalmars.com/d/http://pyd.dsource.org/index.html


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


Re: itertools.groupby

2007-05-28 Thread Raymond Hettinger
On May 28, 8:34 am, 7stud <[EMAIL PROTECTED]> wrote:
> >- there are two more examples on the next page.  those two
> >  examples also give sample inputs and outputs.
>
> I didn't see those.

Ah, there's the rub.  The two sections of examples and recipes
are there for a reason.  This isn't a beginner module.  It is
full of high-speed optimizations applied in a functional style.
That's not for everyone, so it isn't a loss if someone sticks
with writing plain, clear everyday Python instead of an itertool.


Raymond

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


Re: itertools.groupby

2007-05-28 Thread Steve Howell

--- Carsten Haese <[EMAIL PROTECTED]> wrote:

> On Sun, 2007-05-27 at 18:12 -0700, Steve Howell
> wrote:
> > [...] there is no way
> > that "uniquekeys" is a sensible variable [...]
> 
> That's because the OP didn't heed the advice from
> the docs that
> "Generally, the iterable needs to already be sorted
> on the same key
> function."
> 

It was I who was complaining about the variable name
uniquekeys, because the example itself didn't
incorporate a call to sorted().  I would have proposed
two solutions to prevent people from falling into the
trap/pitfall:

   1) Add a call to sorted() in the example.
   2) Rename the variable to
not_necessarily_unique_keys or something like that.

Raymond did the former, so I'm happy.

Although I do think, of course, that people need to
read docs carefully, I think it was a big trap/pitfall
that people might assume the semantics of the SQL
"group by" syntax, so I'm glad that Raymond now calls
out the pitfall, and compares it to the Unix "uniq"
command, which has more similar semantics.



> Suppose hypothetically you wanted to show off a
> really neat example that
> involves chain, izip, and groupby. 

It's hypothetical for itertools, but I can understand
your premise for other modules, where you do more
typically need multiple functions from the module to
provide meaningful examples.

> If the examples
> were forced into the
> page of function synopses, you'd have to duplicate
> it in all three
> functions, or randomly pick one function for which
> your example is an
> example. 

There's no reason why all three functions couldn't
link to the same example on the Examples page, though.

> Having a separate examples page that is not
> arbitrarily
> sectioned by function name makes more sense.
> 

I'd propose a separate examples page that is not
arbitrarily sectioned by function name, or not by
function name, but which is organized according to the
best way to help users use the module.  In the case of
itertools, I'd see the benefit of a separate section
with many examples of groupby(), since it's a very
rich function in its capabilities, and it doesn't
really require anything else from itertools to write
useful programs.


   
Boardwalk
 for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's 
economy) at Yahoo! Games.
http://get.games.yahoo.com/proddesc?gamekey=monopolyherenow  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tix and OS X

2007-05-28 Thread Jeff Reavis
On May 26, 8:51 pm, Kevin Walzer <[EMAIL PROTECTED]> wrote:
> Jeff Reavis wrote:
> > Does python not ship with Tix for OS X? I know there was an issue with
> > 2.5.0 and Tix on Windows, and upgrading to 2.5.1 fixed it.
> > Unfortunately, I seem to have the same issue with OS X and 2.5.1. The
> > error I get is:
>
> >self.tk.eval('package require Tix')
> >_tkinter.TclError: can't find package Tix
>
> > I did find tkinter.so (Tkinter seems to work), but nothing matching
> > tix.so.
> > Is this a known issue? I haven't found any information about it on the
> > web or in this group.
>
> > Thanks in advance.
>
> > This is an Intel Mac, btw.
>
> > -jjr
>
> You have to have the Tcl Tix package installed--the Python module just
> wraps it.
>
> --
> Kevin Walzer
> Code by Kevinhttp://www.codebykevin.com

Thanks, but I still find it strange that the tix so is not included
for the Mac. When dll was missing in Python 2.5 it was considered a
bug (www.python.org/sf/1568240).

-jjr

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


Re: itertools.groupby

2007-05-28 Thread Steve Howell

--- Raymond Hettinger <[EMAIL PROTECTED]> wrote:

> That's not for everyone, so it isn't a loss if
> someone sticks
> with writing plain, clear everyday Python instead of
> an itertool.
> 

I know most of the module is fairly advanced, and that
average users can mostly avoid it, but this is a very
common-antipattern that groupby() solves:

group = []
lastKey = None
for item in items:
newKey = item.key()
if newKey == lastKey:
group.append(item)
elif group:
doSomething(group)
group = []
lastKey = newKey
if group:
doSomething(group)

See this recent thread, for example:

http://mail.python.org/pipermail/python-list/2007-May/442602.html





 

The fish are biting. 
Get more visitors on your site using Yahoo! Search Marketing.
http://searchmarketing.yahoo.com/arp/sponsoredsearch_v2.php
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why isn't this query working in python?

2007-05-28 Thread Gabriel Genellina
En Mon, 28 May 2007 14:53:57 -0300, Dennis Lee Bieber  
<[EMAIL PROTECTED]> escribió:

> On Sun, 27 May 2007 20:35:28 -0400, Carsten Haese <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
>> On Sun, 2007-05-27 at 16:39 -0400, [EMAIL PROTECTED] wrote:
>> > >  sql = """SELECT payment_id FROM amember_payments WHERE
>> > > member_id=%s AND expire_date > NOW() AND completed=1 AND (product_id
>> > >>> 11 AND product_id <21)""", (self.uid)
>
>   It's confusing, as the example shown is not the common form for
> parameter passing on the .execute() call -- without the .execute() it is
> unclear. I presume the .execute() is using *sql to unpack the tuple...

Yes, the original message said self.amember_cursor.execute(*sql)
It IS confusing...

-- 
Gabriel Genellina

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


Re: ten small Python programs

2007-05-28 Thread Stef Mientki

> 
>> The wxPython demo program is written as an
>> interactive tutorial,
>> with a few hundred examples, nicely ordered in
>> groups.
>> The user can view the demo, the code and the help
>> text.
>> The user can also change the code and see the
>> results right away.
>>
> 
> Do you have a link?
wxPython including demos can be downloaded from

   http://www.wxpython.org

but there's no separate page of the demo,
so I made a few screenshots:

http://oase.uci.kun.nl/~mientki/data_www/pic/jalcc/python/wxpython_overview.html

> 
>> It would even be nicer, if everybody could drop
>> her/his examples
>> in a standard way, so they would be automatically
>> incorporated in
>> something like the wxPython interactive demo.
>>
> 
> Can you elaborate?

Well if you see the above demo,
I've the following in mind:
- create a new-demo in a special directory
- add some special keywords in the new-demo, in which treenodes it should popup
- on restart of the demo, the new-demo is added to the tree

cheers,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


User input with a default value that can be modified

2007-05-28 Thread Etienne Hilson
Hello the list :-)

I do a little program that permit the user to manage list of sentences.
This program runs into a linux shell.
The user can add, modify and delete the sentences.

What I want to do is :

When the user want to modify one sentence, I would like to do this :

Modify your sentence : The_sentence_appear_here_followed_by_a_cursor

And the user can go back with the cursor, like in the bash shell,
delete, modify, and when pressing enter, the new value (or the same if
not modified) is put in my variable.

Of course, the first think I did as a newbie was :

new_sentence = raw_input("Modify your sentence : "old_sentence)

But OF COURSE, stupid am I, the user cannot put the cursor back into
the old sentence !

I think about playing with some sophisticated keyboard exercise where
I could program a new input command with a value already appearing as
answer, but I am pretty sure that it exists already.

What do you think about it ?

Actually, it is quite difficult to find anything on it, because the
keywords are not very obvious (input, default answer, ...)

Thank you for your help.

Etienne
-- 
(\__/)
(='.'=)  Ceci est un petit lapin. Copiez/collez-le dans
(")_(")  votre signature pour l'aider à dominer le monde
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: IPyKit, the standalone IPython prompt

2007-05-28 Thread Ville Vainio
Some of you might want to play with IPyKit, especially you need a
swiss-army-knife Python prompt on a (win32) machine where you don't
really want to install anything (python, pyreadline, ipython, PATH
settings...).

It's basically a py2exe'd "preconfigured" IPython.

http://ipython.scipy.org/moin/IpyKit

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


Re: expat parser

2007-05-28 Thread Stefan Behnel
Sebastian Bassi wrote:
> I have this code:
> 
> import xml.parsers.expat
> def start_element(name, attrs):
>print 'Start element:', name, attrs
> def end_element(name):
>print 'End element:', name
> def char_data(data):
>print 'Character data:', repr(data)
> p = xml.parsers.expat.ParserCreate()
> p.StartElementHandler = start_element
> p.EndElementHandler = end_element
> p.CharacterDataHandler = char_data
> fh=open("/home/sbassi/bioinfo/smallUniprot.xml","r")
> p.ParseFile(fh)
> 
> And I get this on the output:
> 
> ...
> Start element: sequence {u'checksum': u'E0C0CC2E1F189B8A', u'length':
> u'393'}
> Character data: u'\n'
> Character data: u'MPKKKPTPIQLNPAPDGSAVNGTSSAETNLEALQKKLEELELDEQQRKRL'
> Character data: u'\n'
> Character data: u'EAFLTQKQKVGELKDDDFEKISELGAGNGGVVFKVSHKPSGLVMARKLIH'
> ...
> End element: sequence
> ...
> 
> Is there a way to have the character data together in one string? I
> guess it should not be difficult, but I can't do it. Each time the
> parse reads a line, return a line, and I want to have it in one
> variable.

Any reason you are using expat and not cElementTree's iterparse?

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


Re: ten small Python programs

2007-05-28 Thread Steve Howell

--- Stef Mientki <[EMAIL PROTECTED]>
wrote:
> > 
> >> It would even be nicer, if everybody could drop
> >> her/his examples
> >> in a standard way, so they would be automatically
> >> incorporated in
> >> something like the wxPython interactive demo.
> >>
> > 
> > Can you elaborate?
> 
> Well if you see the above demo,
> I've the following in mind:
> - create a new-demo in a special directory
> - add some special keywords in the new-demo, in
> which treenodes it should popup
> - on restart of the demo, the new-demo is added to
> the tree
> 

To the extent that you just want a group of people to
be able to organically organize a tree-like collection
of Python examples, you could use a MoinMoin that has
sensible page names and the Local Site Map featured
turn on.  Are you also suggesting the need for
something local, so that you can actually run the
programs?




   
Luggage?
 GPS? Comic books? 
Check out fitting gifts for grads at Yahoo! Search
http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: User input with a default value that can be modified

2007-05-28 Thread half . italian
On May 28, 11:52 am, "Etienne Hilson" <[EMAIL PROTECTED]>
wrote:
> Hello the list :-)
>
> I do a little program that permit the user to manage list of sentences.
> This program runs into a linux shell.
> The user can add, modify and delete the sentences.
>
> What I want to do is :
>
> When the user want to modify one sentence, I would like to do this :
>
> Modify your sentence : The_sentence_appear_here_followed_by_a_cursor
>
> And the user can go back with the cursor, like in the bash shell,
> delete, modify, and when pressing enter, the new value (or the same if
> not modified) is put in my variable.
>
> Of course, the first think I did as a newbie was :
>
> new_sentence = raw_input("Modify your sentence : "old_sentence)
>
> But OF COURSE, stupid am I, the user cannot put the cursor back into
> the old sentence !
>
> I think about playing with some sophisticated keyboard exercise where
> I could program a new input command with a value already appearing as
> answer, but I am pretty sure that it exists already.
>
> What do you think about it ?
>
> Actually, it is quite difficult to find anything on it, because the
> keywords are not very obvious (input, default answer, ...)
>
> Thank you for your help.
>
> Etienne
> --
> (\__/)
> (='.'=)  Ceci est un petit lapin. Copiez/collez-le dans
> (")_(")  votre signature pour l'aider à dominer le monde

Check into the readline module.  This is what I came up with.  A
second thread injects the text into the open readline instance.
Hopefully the experts will show the _right_ way to do it.

import readline, threading
import time

class write(threading.Thread):
def __init__ (self, s):
threading.Thread.__init__(self)
self.s = s

def run(self):
time.sleep(.01)
readline.insert_text(self.s)
readline.redisplay()

write("Edit this sentence").start()
s = raw_input("prompt:")

print s

~Sean

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


Re: itertools.groupby

2007-05-28 Thread Raymond Hettinger
> > That's not for everyone, so it isn't a loss if
> > someone sticks
> > with writing plain, clear everyday Python instead of
> > an itertool.
>
> I know most of the module is fairly advanced, and that
> average users can mostly avoid it, but this is a very
> common-antipattern that groupby() solves:

I think the OP would have been better-off with plain
vanilla Python such as:

   See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259173

Raymond

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


Re: User input with a default value that can be modified

2007-05-28 Thread half . italian
On May 28, 11:52 am, "Etienne Hilson" <[EMAIL PROTECTED]>
wrote:
> Hello the list :-)
>
> I do a little program that permit the user to manage list of sentences.
> This program runs into a linux shell.
> The user can add, modify and delete the sentences.
>
> What I want to do is :
>
> When the user want to modify one sentence, I would like to do this :
>
> Modify your sentence : The_sentence_appear_here_followed_by_a_cursor
>
> And the user can go back with the cursor, like in the bash shell,
> delete, modify, and when pressing enter, the new value (or the same if
> not modified) is put in my variable.
>
> Of course, the first think I did as a newbie was :
>
> new_sentence = raw_input("Modify your sentence : "old_sentence)
>
> But OF COURSE, stupid am I, the user cannot put the cursor back into
> the old sentence !
>
> I think about playing with some sophisticated keyboard exercise where
> I could program a new input command with a value already appearing as
> answer, but I am pretty sure that it exists already.
>
> What do you think about it ?
>
> Actually, it is quite difficult to find anything on it, because the
> keywords are not very obvious (input, default answer, ...)
>
> Thank you for your help.
>
> Etienne
> --
> (\__/)
> (='.'=)  Ceci est un petit lapin. Copiez/collez-le dans
> (")_(")  votre signature pour l'aider à dominer le monde

Check into the readline module.  This is what I came up with.  A
second thread injects the text into the open readline instance.
Hopefully the experts will show the _right_ way to do it.

import readline, threading
import time

class write(threading.Thread):
def __init__ (self, s):
threading.Thread.__init__(self)
self.s = s

def run(self):
time.sleep(.01)
readline.insert_text(self.s)
readline.redisplay()

write("Edit this sentence").start()
s = raw_input("prompt:")

print s

~Sean

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


Re: itertools.groupby

2007-05-28 Thread Alex Martelli
Steve Howell <[EMAIL PROTECTED]> wrote:
   ...
> for has_chars, frags in itertools.groupby(lines,
> lambda x: len(x) > 0):

Hmmm, it appears to me that itertools.groupby(lines, bool) should do
just the same job, just a bit faster and simpler, no?


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


Re: Is PEP-8 a Code or More of a Guideline?

2007-05-28 Thread Alex Martelli
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> Historically, it's only Java and the Windows world (including non-
> standard Windows-style C++) that use forcedCase significantly (C#
> draws from both).

I remember meeting that style first in the X Window System (now commonly
known as X11, but it was around for a few years before the 11 arrived),
which is a little bit older than Windows and WAY older than Java.  I
don't know if X was the first project to use that style consistently.


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


Re: itertools.groupby

2007-05-28 Thread Gordon Airporte
7stud wrote:
> Bejeezus.  The description of groupby in the docs is a poster child
> for why the docs need user comments.  Can someone explain to me in
> what sense the name 'uniquekeys' is used this example:
> 

This is my first exposure to this function, and I see that it does have 
some uses in my code. I agree that it is confusing, however.
IMO the confusion could be lessened if the function with the current 
behavior were renamed 'telescope' or 'compact' or 'collapse' or 
something (since it collapses the iterable linearly over homogeneous 
sequences.)
A function named groupby could then have what I think is the clearly 
implied behavior of creating just one iterator for each unique type of 
thing in the input list, as categorized by the key function.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ten small Python programs

2007-05-28 Thread Stef Mientki
Steve Howell wrote:
> --- Stef Mientki <[EMAIL PROTECTED]>
> wrote:
 It would even be nicer, if everybody could drop
 her/his examples
 in a standard way, so they would be automatically
 incorporated in
 something like the wxPython interactive demo.

>>> Can you elaborate?
>> Well if you see the above demo,
>> I've the following in mind:
>> - create a new-demo in a special directory
>> - add some special keywords in the new-demo, in
>> which treenodes it should popup
>> - on restart of the demo, the new-demo is added to
>> the tree
>>
> 
> To the extent that you just want a group of people to
> be able to organically organize a tree-like collection
> of Python examples, you could use a MoinMoin that has
> sensible page names and the Local Site Map featured
> turn on.  Are you also suggesting the need for
> something local, so that you can actually run the
> programs?

I don't know MoinMoin,
but the answer is Yes (although maybe not for your ten snippets).
First of all I think all programmers keep there own collection of code snippets,
which much more valuable then "all the code code snippets from everyone".
Secondly, Python is nowadays not only used by programmers,
but also by e.g. Scientific users (former MatLab users),
who are not interested in the code itself,
but just in the results of that particular code.
For these people a lot of example programs,
for which they can easily see the results,
make some small changes and see the result again,
would be a wonderful addition.

just my 2 cents,
cheers,
Stef Mientki


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


Re: itertools.groupby

2007-05-28 Thread Paul Rubin
Gordon Airporte <[EMAIL PROTECTED]> writes:
> This is my first exposure to this function, and I see that it does
> have some uses in my code. I agree that it is confusing, however.
> IMO the confusion could be lessened if the function with the current
> behavior were renamed 'telescope' or 'compact' or 'collapse' or
> something (since it collapses the iterable linearly over homogeneous
> sequences.)

It chops up the iterable into a bunch of smaller ones, but the total
size ends up the same.  "Telescope", "compact", "collapse" etc. make
it sound like the output is going to end up smaller than the input.

There is also a dirty secret involved , which is that the
itertools functions (including groupby) are mostly patterned after
similarly named functions in the Haskell Prelude, which do about the
same thing.  They are aimed at helping a similar style of programming,
so staying with similar names IMO is a good thing.

> A function named groupby could then have what I think is the clearly
> implied behavior of creating just one iterator for each unique type of
> thing in the input list, as categorized by the key function.

But that is what groupby does, except its notion of uniqueness is
limited to contiguous runs of elements having the same key.
-- 
http://mail.python.org/mailman/listinfo/python-list


Tkinter error

2007-05-28 Thread BartlebyScrivener
Finally started trying to build a simple gui form for inserting text
data into a mysql db of quotations.

I found this nice Tkinter tutorial,

http://www.ibiblio.org/obp/py4fun/gui/tkPhone.html

but midway I'm getting an error.

from Tkinter import *

 >>> win = Tk()
>>> f = Frame(win)
>>> b1 = Button(f, "One")

Traceback (most recent call last):
  File "", line 1, in ?
  File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1936, in __init__
Widget.__init__(self, master, 'button', cnf, kw)
  File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1859, in __init__
BaseWidget._setup(self, master, cnf)
  File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1839, in _setup
if cnf.has_key('name'):
AttributeError: 'str' object has no attribute 'has_key'

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


Re: ten small Python programs

2007-05-28 Thread Steve Howell

--- Stef Mientki <[EMAIL PROTECTED]> > >

> I don't know MoinMoin,
> but the answer is Yes (although maybe not for your
> ten snippets).
> First of all I think all programmers keep there own
> collection of code snippets,
> which much more valuable then "all the code code
> snippets from everyone".

Agreed.

> Secondly, Python is nowadays not only used by
> programmers,
> but also by e.g. Scientific users (former MatLab
> users),
> who are not interested in the code itself,
> but just in the results of that particular code.
> For these people a lot of example programs,
> for which they can easily see the results,
> make some small changes and see the result again,
> would be a wonderful addition.
> 

In your own personal use, what are some
libraries/techniques/etc. that you think could benefit
from some kind of more organized presentation of
example programs (or better way of showing how the
examples work, etc.)?  Are you part of the Scientific
community?

How new are you to Python?  I do think
newbies/intermediates/advanceds all have different
needs.

 


   
Building
 a website is a piece of cake. Yahoo! Small Business gives you all the tools to 
get online.
http://smallbusiness.yahoo.com/webhosting 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: itertools.groupby

2007-05-28 Thread Steve Howell

--- Paul Rubin <"http://phr.cx"@NOSPAM.invalid> wrote:
> 
> 
> But that is what groupby does, except its notion of
> uniqueness is
> limited to contiguous runs of elements having the
> same key.

It occurred to me that we could also rename the
function uniq(), or unique(), after its Unix
counterpart, but then I though better of it.  As one
of the folks who was making a bit of noise about the
groupby() semantics before, I'm really fine with the
name now that the docs make it a little more clear how
it behaves.




  

Park yourself in front of a world of choices in alternative vehicles. Visit the 
Yahoo! Auto Green Center.
http://autos.yahoo.com/green_center/ 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter error

2007-05-28 Thread Peter Otten
BartlebyScrivener wrote:

> Finally started trying to build a simple gui form for inserting text
> data into a mysql db of quotations.
> 
> I found this nice Tkinter tutorial,
> 
> http://www.ibiblio.org/obp/py4fun/gui/tkPhone.html
> 
> but midway I'm getting an error.
> 
> from Tkinter import *
> 
>  >>> win = Tk()
 f = Frame(win)
 b1 = Button(f, "One")
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1936, in __init__
> Widget.__init__(self, master, 'button', cnf, kw)
>   File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1859, in __init__
> BaseWidget._setup(self, master, cnf)
>   File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1839, in _setup
> if cnf.has_key('name'):
> AttributeError: 'str' object has no attribute 'has_key'

Hmm, there must have been an update to that tutorial after you read it:

"""
>>> b1 = Button(win,text="One")
>>> b2 = Button(win,text="Two")


The class Button takes the parent window as the first argument. As we will
see later other objects, such as frames, may also act as parents. The rest
of the arguments are passed by keyword and are all optional.
"""

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


Re: itertools.groupby

2007-05-28 Thread Steve Howell

--- Raymond Hettinger <[EMAIL PROTECTED]> wrote:

> > > That's not for everyone, so it isn't a loss if
> > > someone sticks
> > > with writing plain, clear everyday Python
> instead of
> > > an itertool.
> >
> > I know most of the module is fairly advanced, and
> that
> > average users can mostly avoid it, but this is a
> very
> > common-antipattern that groupby() solves:
> 
> I think the OP would have been better-off with plain
> vanilla Python such as:
> 
>See
>
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259173
> 

That recipe implements SQL-like Group By, but it's the
uniq-like reimplementation of groupby() that I think
is error prone.

The OP was writing code that wanted the uniq-like
semantics.




   
Boardwalk
 for $500? In 2007? Ha! Play Monopoly Here and Now (it's updated for today's 
economy) at Yahoo! Games.
http://get.games.yahoo.com/proddesc?gamekey=monopolyherenow  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: itertools.groupby

2007-05-28 Thread Steve Howell

--- Alex Martelli <[EMAIL PROTECTED]> wrote:

> Steve Howell <[EMAIL PROTECTED]> wrote:
>...
> > for has_chars, frags in itertools.groupby(lines,
> > lambda x: len(x) > 0):
> 
> Hmmm, it appears to me that itertools.groupby(lines,
> bool) should do
> just the same job, just a bit faster and simpler,
> no?
> 

Agreed.  

I updated the webpages with your change (after testing
it in 2.5):

http://wiki.python.org/moin/SimplePrograms




   
Take
 the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, 
photos & more. 
http://mobile.yahoo.com/go?refer=1GNXIC
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is PEP-8 a Code or More of a Guideline?

2007-05-28 Thread Steven D'Aprano
On Mon, 28 May 2007 14:12:33 -0700, Alex Martelli wrote:

> [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> 
>> Historically, it's only Java and the Windows world (including non-
>> standard Windows-style C++) that use forcedCase significantly (C#
>> draws from both).
> 
> I remember meeting that style first in the X Window System (now commonly
> known as X11, but it was around for a few years before the 11 arrived),
> which is a little bit older than Windows and WAY older than Java.  I
> don't know if X was the first project to use that style consistently.

There was also Hypercard from Apple in (by memory) 1988. Although case was
not significant, handlers were usually written mouseDown, mouseUp,
openStack, openCard, etc.


-- 
Steven.

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


Re: itertools.groupby

2007-05-28 Thread Paul Rubin
Raymond Hettinger <[EMAIL PROTECTED]> writes:
> I think the OP would have been better-off with plain
> vanilla Python such as:
> 
>See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/259173

But that recipe generates the groups in a random order depending on
the dict hashing, instead of keeping them in the original sequence's
order, which the OP's application might well require.
itertools.groupby really is the right thing.  I agree that itertools
is not the easiest module in the world for beginning programmers to
understand, but every serious Python user should spend some time
figuring it out sooner or later.  Iterators and itertools really turn
Python into a higher-level language than it was before, giving
powerful and streamlined general-purpose mechanisms that replace a lot
of special-purpose hand-coding that usually ends up being a lot more
work to debug in addition to bloating the user's code.  Itertools
should by no means be thought of as just a performance hack.  It makes
programs smaller and sharper.  It quickly becomes the One Obvious Way
To Do It.

In my past few kloc of Python, I think I've written just one or two
"class" statements.  I used to use class instances all the time, to
maintain little bits of state that had to be held between different
operations in a program.  Using itertools means I now tend to organize
entire programs as iterator pipelines so that all the data runs
"through the goose" exactly once and there is almost no need to
maintain any state anywhere outside the scope of simple function
invocations.  There are just fewer user-written moving parts when a
program is written that way, and therefore fewer ways for the program
to go wrong.  Messy edge cases that used to take a lot of thought to
handle correctly now need no attention at all--they just handle
themselves.

Also I think it's generally better to use a documented standard
library routine than a purpose-written routine or even a downloaded
recipe, since the stdlib routine will stay easily available from one
project to another and as the user gains experience with it, it will
become more and more powerful in his or her hands.  

Also, these days I think I'd write that recipe with a defaultdict
instead of setdefault, but that's new with Python 2.5.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >