Re: lambda closure question

2005-02-19 Thread Carl Banks
Ted Lilley wrote:
 What I want to do is pre-load functions with arguments by iterating
 through a list like so:

 class myclass:
 ...pass
 def func(self, arg):
 ...print arg
 mylist = [my, sample, list]
 for item in mylist:
 ...setattr(myclass, item, lamdba self: func(self, item))

[snip]

 Unfortunately, it doesn't work.  It seems the closure keeps track of
 the variable fed to it dynamically - if the variable changes after
the
 lambda is created, the lambda still references the _variable_ not the
 original _value_ and so gets the new value like so:

 obj.sample()
 list
 obj.my()
 list

 At least, that's the explanation I'm deducing from this behavior.

And that's the correct explanation, chief.


 Assuming that's the way Guido intended it to be (about as dynamic as
it
 can get), I'm at a loss to do what _I_ want it to do.  In fact, I
don't
 think there's any way to generate the lambdas properly without coding
 in the name as a literal string, since any attempt to use a variable
 reference will always get modified as the loop iterates.

It is intended that way.  As an example of why that is: consider a
nested function called printvars() that you could insert in various
places within a function to print out the value of some local variable.
 If you did that, you wouldn't want printvars to print the values at
the time it was bound, would you?

Anyways, this can be worked around, but I'd suppose it's not as
convenient as you'd like.  (You could define crystalize outside the
loop, but I have it in the loop to keep it near the place where you
need it.)

. mylist = [my,sample,list]
. for item in mylist:
. def crystalize(x):
. return lambda self: func(self,x)
. setattr(myclass,item,crystalize(item))

If you're hellbent on only using lambda, that can be done too:

. setattr(myclass,item,(lambda x:(lambda self:
func(self,x)))(item))

You may not be aware of it, but what you're trying to do is called
currying; you might want to search the Python Cookbook for recipes on
it.


-- 
CARL BANKS

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


Re: lambda closure question

2005-02-19 Thread jfj
Carl Banks wrote:
Ted Lilley wrote:

Unfortunately, it doesn't work.  It seems the closure keeps track of
the variable fed to it dynamically - if the variable changes after
 [...]
At least, that's the explanation I'm deducing from this behavior.

And that's the correct explanation, chief.

It is intended that way.  As an example of why that is: consider a
nested function called printvars() that you could insert in various
places within a function to print out the value of some local variable.
 If you did that, you wouldn't want printvars to print the values at
the time it was bound, would you?
Allow me to disagree (and start a new confused with closures thread:)
We know that python does not have references to variables. To some
newcomers this may seem annoying but eventually they understand the
pythonic way and they do without them. But in the case of closures
python supports references!
Nested functions, seem to do two independent things:
  1) reference variables of an outer local scoope
  2) are functions bound dynamically to constants
These two are independent because in:
##
def foo():
def nested():
 print x
f = nested
x = 'sassad'
f()
x = 'aafdss'
f()
return f
##
once foo() returns there is no way to modify 'x'!
It becomes a kind of constant.
So IMVHO, one will never need both features. You either want to
return a function bound to a local value *xor* use a local
function which has access to locals as if they were globals.
Supposing the default behaviour was that python does what Carl
suggests (closures don't keep track of variables), would there
be an elegant pythonic way to implement nested functions that
reference variables from their outer scope? (although if find
this little useful and un-pythonic)
Personally, i think that this is a problem with the way lisp
and other languages define the term closure. But python is
different IMO, and the ability to reference variables is not
useful.
cheers,
jfj
---
# the president
--
http://mail.python.org/mailman/listinfo/python-list


Re: re.compile and very specific searches

2005-02-19 Thread Denis S. Otkidach
On Fri, 18 Feb 2005 13:14:28 -0500
rbt [EMAIL PROTECTED] wrote:

 Is it possible to use re.compile to exclude certain numbers? For 
 example, this will find IP addresses:
 
 ip = re.compile('\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}')
 
 But it will also find 999.999.999.999 (something which could not 
 possibly be an IPv4 address). Can re.compile be configured to filter 
 results like this out?

Try this one: 
re.compile(r'\b%s\b' % r'\.'.join(['(?:(?:2[0-4]|1\d|[1-9])?\d|25[0-5])']*4))

-- 
Denis S. Otkidach
http://www.python.ru/  [ru]
-- 
http://mail.python.org/mailman/listinfo/python-list


±M·~ºô­¶±H¦sªA°È ¦P¨B¤ä´© PHP+MySQL, Access+ASP, ASP.NET, CGI, SSI ¹q¶l¯f¬r¹LÂo, ©U§£¹q¶l¹LÂo ¤ÎWebMail ..............................................................................................................................................................................................................................................................................................

2005-02-19 Thread dummyboy
©Ò¦³¦b¥»¤ë§C«e¥Ó½Ðªº¨ä¥¦¤½¥qÂಾ«È¤á§Y¦h°e±z¤T­Ó¤ëªA°È
¤ä´© PHP+MySQL, Access+ASP, ASP.NET, CGI, SSI ¹q¶l¯f¬r¹LÂo, ©U§£¹q¶l¹LÂo ¤Î
WebMail µ¥..
¥»¤ë§C«e¥Ó½ÐW1000§Y°e­º¦¸¦w¸ËÁʪ«¨®µ{¦¡ osc.
http://shop2.uhostnet.com

¨C¤ë¥u»Ý $20 °_

­º­¶
http://www.uhostnet.com

·s«È¤á¶}³q¼ËªO
http://dummy.uhostnet.com

·s«Ȥᴣ¨Ñ¤C¤Ñ§K¶O«Ø¯¸´Á¡C 
¥i¨Ï¥Î¥»¤½¥q§K¶O´£¨Ñªº°Æ°ì¦W¡C 
ªA°È­p¹º¶R¤Q°e¤G¡A¤Z¹wú¤Q­Ó¤ëªA°È¤ë¶O¡A¦h°e¨â­Ó¤ë¡C 
²{§Y¥Ó¨ä¥¦¤½¥qÂà¥Î§Ú­Ì¡A§Y¦h°e±z¤T­Ó¤ëªA°È¡C(¥ô¦ó°ì¦WÂಾ)
¥H¤W­p¹º¥þ±Ä¥Î¤¤¤åWIN2003¥­¥x¡A«È¤á¥ç¥i¿ï¥Î¥»¤½¥qªºLinux¥­¥xªA°È­p¹º¡C 

ªþ°e¹ê¥Îµ{¦¡
ASP ¯d¨¥Ã¯,²á¤Ñ«Ç,ASP ¤H¼Æ¾¹,PHP ¤H¼Æ¾¹,ASP ºô¤W¹q¶lªí®æ,ASP 
Àɮ׺޲zµ{¦¡,ºô¤W°Ó©±,©ç½æ¨t²Î¤Î¦U´Ú½×¾Âµ{¦¡..

¨C¤ë $20 ºô­¶±H¦sªA°È
Basic Plan W200: (¨C¤ë $20)
-- 200MB ºô­¶ªÅ¶¡
-- µL­­¹q¶l«H½c
-- µL­­¸ê®Æ¶Ç¿é¶q
-- ¤ä´© ASP+Access / CGI
-- ¹q¶l¯f¬r¹LÂo¨t²Î
-- ©U§£¹q¶l¹LÂo¨t²Î
http://www.uhostnet.com/modules.php?name=servicefile=indexfunc=windetailsplan=A

Windows W300: (¨C¤ë $38)
-- [EMAIL PROTECTED]
-- 300MB ºô­¶ªÅ¶¡
-- µL­­¹q¶l«H½c
-- µL­­¸ê®Æ¶Ç¿é¶q
-- ¤ä´© PHP+MySQL, ASP+ACCESS, CGI, SSI
-- 1 ­Ó MySQL ¸ê®Æ®w (5MB)
-- ¹q¶l¯f¬r¹LÂo¨t²Î
-- ©U§£¹q¶l¹LÂo¨t²Î
http://www.uhostnet.com/modules.php?name=servicefile=indexfunc=windetailsplan=B

Windows W500: (¨C¤ë $48)
-- [EMAIL PROTECTED]
-- ¤lºô°ì 3 ­Ó (¼v®g¤£¦P¥Ø¿ý)
-- 500MB ºô­¶ªÅ¶¡
-- µL­­¹q¶l«H½c
-- µL­­¸ê®Æ¶Ç¿é¶q
-- ¤ä´© PHP+MySQL, ASP+ACCESS, CGI, SSI
-- 1 ­Ó MySQL ¸ê®Æ®w (10MB)
-- ¹q¶l¯f¬r¹LÂo¨t²Î
-- ©U§£¹q¶l¹LÂo¨t²Î
http://www.uhostnet.com/modules.php?name=servicefile=indexfunc=windetailsplan=C

Windows W800: (¨C¤ë $58)
-- [EMAIL PROTECTED]
-- ¤lºô°ì 5 ­Ó (¼v®g¤£¦P¥Ø¿ý)
-- 800MB ºô­¶ªÅ¶¡
-- µL­­¹q¶l«H½c
-- µL­­¸ê®Æ¶Ç¿é¶q
-- ¤ä´© PHP+MySQL, ASP+ACCESS, CGI, SSI
-- 1 ­Ó MySQL ¸ê®Æ®w (20MB)
-- ¹q¶l¯f¬r¹LÂo¨t²Î
-- ©U§£¹q¶l¹LÂo¨t²Î
http://www.uhostnet.com/modules.php?name=servicefile=indexfunc=windetailsplan=D

Windows W1000: (¨C¤ë $68)
-- [EMAIL PROTECTED]
-- ¤lºô°ì 10 ­Ó (¼v®g¤£¦P¥Ø¿ý)
-- 1GB ºô­¶ªÅ¶¡
-- µL­­¹q¶l«H½c
-- µL­­¸ê®Æ¶Ç¿é¶q
-- ¤ä´© PHP+MySQL, ASP+ACCESS, CGI, SSI
-- 1 ­Ó MySQL ¸ê®Æ®w (50MB)
-- ¹q¶l¯f¬r¹LÂo¨t²Î
-- ©U§£¹q¶l¹LÂo¨t²Î
-- °e­º¦¸¦w¸Ë½×¾Âµ{¦¡©Î¶W±jºô¤W°Ó©±¨t²Î
http://www.uhostnet.com/modules.php?name=servicefile=indexfunc=windetailsplan=E


«È ¤á ¦C ªí : http://www.uhostnet.com/modules.php?name=clients
.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I get message filename from a Maildir mailbox stream?

2005-02-19 Thread Phil Jackson
[EMAIL PROTECTED] writes:

 Is there a way to figure out what filename an email object points to
 in a qmail style Maildir directory?

What do you mean bu email object? Surely if you are iterating a
Maildir then you should have the filename. Or am I misunderstanding
what you mean?

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


Re: Chart Director?

2005-02-19 Thread km
Hi all,
Chart Director is a good module to implement graphs using in python.
i have been using it since 6 months for scientific data visualisation.
great module !!!
regards,
KM
--
On Sat, Feb 19, 2005 at 08:22:19AM +0100, Vincent Wehren wrote:
 [EMAIL PROTECTED] wrote:
 Does anyone here have experience with Chart Director
 (http://www.advsofteng.com/index.html)?   I'm thinking about purchasing
 it and looking for any feedback from the Python community.  Thanks
 
 
 Since ChartDirector is not exactly open source nor found its origin in a 
 Python setting, my uneducated guess is that it will mostly be companies 
 that use ChartDirector.
 
 However, from that vantage-point, ChartDirector is well-documented, has 
 lots of examples, and is great value for the money; it's pretty straight 
 forward, it covers all Python versions from 1.52 - 2.4, and the license 
 generally encompasses all other language bindings, too (all being at 
 version 4.0 except for the C++ version which is currently still at 3.04).
 
 Still, you should just try it for what you are planning to use it /for/ 
 and see if it meets /your/ specific needs.
 
 --
 Vincent Wehren
 
 
 
 
 
 -- 
 http://mail.python.org/mailman/listinfo/python-list


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


Re: lambda closure question

2005-02-19 Thread Carl Banks

jfj wrote:
 Carl Banks wrote:
  Ted Lilley wrote:
 
 
 Unfortunately, it doesn't work.  It seems the closure keeps track
of
 the variable fed to it dynamically - if the variable changes after
   [...]
 
 At least, that's the explanation I'm deducing from this behavior.
 
 
  And that's the correct explanation, chief.

 
  It is intended that way.  As an example of why that is: consider a
  nested function called printvars() that you could insert in
various
  places within a function to print out the value of some local
variable.
   If you did that, you wouldn't want printvars to print the values
at
  the time it was bound, would you?

 Allow me to disagree (and start a new confused with closures
thread:)

 We know that python does not have references to variables. To some
 newcomers this may seem annoying but eventually they understand the
 pythonic way and they do without them. But in the case of closures
 python supports references!

That's right.  It's called Practicality beats purity.

The question is what's more important: to be able to use a nested
function to reference the outer scope, or to be able to use a nested
function as a closure inside the function it was defined in?  (Both
approaches effectively allow using a nested function as a closure if
it's used after the function returns.)

The Gods decided, for practical reasons, the former was more important.
 My experience bears this out: I find that about half the nested
functions I use are to reference an outer scope, half I return as a
closure.  Only once or twice did I try to use a nested function inside
the defining function.  I would guess this is more or less typical of
how nested functions are used.  If so, it was the right decision.


-- 
CARL BANKS

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


Re: duplicate docstrings

2005-02-19 Thread Brian van den Broek
Steven Bethard said unto the world upon 2005-02-18 13:58:
I have two classes that implement the same interface, e.g. something like:
class C(object):
def foo(self):
Foo things
...
def bar(self):
Bar things
...
def baz(self):
Baz things in a C manner
...
class D(object):
def foo(self):
Foo things
...
def bar(self):
Bar things
...
def baz(self):
Baz things in a D manner
...
It bothers me that I'm basically writing the same docstrings multiple 
times.  I guess what I really want to do is just write the docstrings 
for the interface I'm describing, and only supply docstrings in the 
classes when they need to differ from the interface docstrings.

Is there a good way to do this?  If it's necessary, I can have C and D 
inherit from another class...

STeVe
Hi, I'm new to thinking in classes, and may not have understood your 
need. But does this help:

IDLE 1.1
 class Spam:
'''I'm a very spammy docstring'''
pass
 class Ham:
__doc__ = Spam.__doc__

 help(Ham)
Help on class Ham in module __main__:
class Ham
 |  I'm a very spammy docstring

best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can I get message filename from a Maildir mailbox stream?

2005-02-19 Thread Michael Josephson
a way to figure out what filename an email object points to in a 
qmail style Maildir directory?

Assuming you're using the mailbox module from the standard Python
library, the Message objects you get back provide access to the file
object as an instance variable called fp. So if you have:

maildir = mailbox.Maildir(/home/mike/Maildir)
message = maildir.next()

The filename is message.fp.name

Note that the file object is open when you are in this state so you
may want to close it before you do a move/delete etc.

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


Re: unicode and socket

2005-02-19 Thread Serge Orlov
[EMAIL PROTECTED] wrote:
 It's really funny, I cannot send a unicode stream throuth socket with
 python while all the other languages as perl,c and java can do it.

You may really start laughing loudly wink after you find out that you
can  send arbitrary python objects over sockets. If you want language
specific way of sending objects, see Irmen's first answer: use pickle.

 then, how about converting the unicode string to a binary stream?

Sure, there are already three answers in this thread that suggest you
to do that. Use encode method of unicode strings.

 It is possible to send a binary through socket with python?

Sure. If it wouldn't be possible to send bytes through sockets with Python
what else do you think could be sent? Perhaps you're confused that
bytes are stored in byte strings in Python, which are often called strings in
documentation and conversations? It will be fixed in Python 3.0, but
these days you have to store bytes in str type.

  Serge.




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


Re: - E02 - Support for MinGW Open Source Compiler

2005-02-19 Thread Ilias Lazaridis
A.B., Khalid wrote:
Ilias Lazaridis wrote:
The first step is to make a pyMinGW project.
You are mistaken. The first steps are the following:
[...] - (nonrelevant comments)
3) Realizing that there _is_ already a project called pyMinGW! That it
does not fit your requirements-- whatever these maybe-- is an
altogether different issue. The fact of the matter remains that a
project _does_ exist, one which people (including myself) do in fact
use; and because it does exist there is no reason to make it.
[...]
I've already understood your viewpoint.
I've realized, that there is a single-person-centric project
pyMinGW which does not encourage collaboration (due to missing public 
resources like mailinglist).

My requirements about an open-source project (or sub-project) are very 
simple:
  a communication resource,
  a code-repository,
  an issue-tracking-system.

I've suggested you to transform your personal project to a collaborative 
project, starting with an dedicated mailinglist etc.:


thank you for your comments.
I will express my suggestion more practically
  * as a first step, I would setup a pyMinGW mailinglist
* intrested people can come together an communicate
  * as a second step, I would setup an SVN
* intrested projects could get your patch via SVN
  * as a third step, I would find intrested contributors
* which would help testing
* which would help you with coding
All this could happen without (or with very low) efforts for you.

-
You have the right to refuse this.
I (and any other reader) have the right to derive our conclusions about 
you and the reasons that you refuse a _real_ collaborative work.

.
--
pyMinGW:
http://jove.prohosting.com/iwave/ipython/pyMinGW.html
.
--
http://lazaridis.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Access to formatting controls from within __repr__ or __str__?

2005-02-19 Thread Serge Orlov
Dan Sommers wrote:
 On 18 Feb 2005 01:25:06 -0800,
 Serge Orlov [EMAIL PROTECTED] wrote:

 Dan Sommers wrote:

 So my question is:  Is there a way to pass options through a
 format string to the __str__ and __repr__ functions?  For example,
 can I define my own alternate form for use with the '#' formatting
 character, so that '%#s' generates output according to SI
 guidelines?

 You can create your own class FmtTemplate like string.Template was
 done in python 2.4: http://docs.python.org/lib/node105.html

 That looks interesting.  Perhaps that will push me into upgrading to
 2.4 sooner rather than later (I'm *not* looking forward to rebuilding
 all my extensions...).

You don't need to upgrade to Python 2.4. string.Template is a pure
Python code (about 130 lines) and it looks like it's Python 2.2
compatible. My suggestion was to grab it and hack it to add the
feature you want and then keep it in your own library.

  Serge.


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


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-19 Thread Martin v. Löwis
Ilias Lazaridis wrote:
My questions:
It appears that nobody has answered the questions, yet.
a) Why does the Python Foundation not provide additionally a binary 
version, compiled with MinGW or another open-source compiler?
We don't have the resources to do that.
b) Why does the Python Foundation not ensure, that the python 
source-code is directly compilable with MinGW?
In the past, we did not do that because we did not know how to do it.
With Python 2.4.1, we now had a contribution that should allow direct
compilation of extensions using MingW.
c) Why are the following efforts not _directly_ included in the python 
source code base?

http://jove.prohosting.com/iwave/ipython/pyMinGW.html
I believe this was because it was never contributed to Python.
d) Is it really neccessary that I dive into such adventures, to be able 
to do the most natural thing like: developing python extensions with 
MinGW?

http://starship.python.net/crew/kernr/mingw32/Notes.html
No. These instructions are outdated.
e) Is there any official statement available regarding the msvcr71.dll 
and other MS licensing issues?

[see several threads [Python-Dev] Is msvcr71.dll re-redistributable?]
http://mail.python.org/pipermail/python-dev/2005-February/thread.html
No, there isn't.
f) Are there any official (Python Foundation) statements / rationales 
available, which explain why the MinGW compiler is unsupported, although 
parts of the community obviously like to use it?

http://groups-beta.google.com/group/comp.lang.python/msg/dc3474e6c8053336
The official statement is that the MingW compiler is supported, indeed.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


[perl-python] exercise: partition a list by equivalence

2005-02-19 Thread Xah Lee
here's the answer to the partition by equivalence exercise.

---

# Perl code

sub merge($) {
my @pairings = @{$_[0]};

my @interm; # array of hashs

# chop the first value of @pairings into @interm
$interm[0]={$pairings[0][0]='x'}; ${interm[0]}{$pairings[0][1]}='x';
shift @pairings;

 N1: for my $aPair (@pairings) {
 for my $aGroup (@interm) {
 if (exists ${$aGroup}{$aPair-[0]})
{${$aGroup}{$aPair-[1]}='x'; next N1}
 if (exists ${$aGroup}{$aPair-[1]})
{${$aGroup}{$aPair-[0]}='x'; next N1}
 }
 push @interm, {$aPair-[0]='x'}; ${interm[-1]}{$aPair-[1]}='x';
 }

my @fin = shift @interm;

N2: for my $group (@interm) {
for my $newcoup (@fin) {
foreach my $k (keys %$group) {
if (exists ${$newcoup}{$k}) {map { ${$newcoup}{$_}='x'}
(keys %$group); next N2;}
}
}
push @fin, $group;
}
return map {[keys (%$_)]} @fin;
}

---
# Here's a direct translation of the Perl code above into python:
©
©def merge(pairings): # pairings is a list of couples. e.g.
[(9,2),(7,6),...]
©
©# interm is a list of groups. Each group is a list that hold
©# equivalent numbers. interm stands for interim result. Each
group
©# is a dictionary. Keys are numbers, values are all dummy
©# 'x'. Dictionary is used for ease of dealing with duplicates or
©# checking existence.
©interm=[];
©
©# move first pair of pairings into interm as the first group
©interm.append({pairings[0][0]:'x', pairings[0][1]:'x'}) ; del
pairings[0]
©
©# go thru pairings. For each pair, check if it is in any group in
©# interm. If any part of pair is in a group, then add the other
©# part into that group. If no part of the pair is in any group,
©# then add this pair into interm as a new group.
©for aPair in pairings:
©for aGroup in interm:
©if (aGroup.has_key(aPair[0])): aGroup[aPair[1]]='x';
break
©if (aGroup.has_key(aPair[1])): aGroup[aPair[0]]='x';
break
©else: interm.append( {aPair[0]:'x'} );
interm[-1][aPair[1]]='x'
©
©# now make another pass of the groups in interm, because some
pair
©# that may connect two groups (i.e. with one element in one
group,
©# and second element in another group), yet the pair is simply
©# consumed by a group.
©# This pass will check if there are any element in any other
©# group, if so, such two groups will be unioned. In this pass, we
©# move things from interm into fin. fin==final.
©fin=[]; fin.append(interm.pop(0))
©for group in interm:
©for newcoup in fin:
©for k in group.keys():
©if newcoup.has_key(k):
©for kk in group.keys(): newcoup[kk]='x';
©break
©break
©fin.append(group)
©
©# now turn the dictionaries into lists for return value
©result=[];
©for group in fin: result.append(group.keys())
©return result
©
---
I wrote this (Perl) program in 2003-09, and now basically forgot all
about the internals. The original Perl code does not have inline
comments, nor public consumable documentation as this is my own
project. In the process of translation and the publication and
explanation on this page, i eventually have to re-acquaint the
algorithm i used as i go thru the lines. I was thinking of a quick
brainless translation word-for-word, but that turned out not possible
as i run into problems.

(While i'm learning Python, i run into frustrations with the Python
Documentation. (although it has far more quality than Perl
documentations). The frustrations with documentations will be appended
to this page later: How to write a tutorial )

The translation problem i run into is this. In Perl, there's a GOTO
construct where in a loop one can say break XYZ to jump to a
arbitrary outer loop labeled XYZ. Python has break but does not
provide a GOTO jump as in Perl. In the process, i have to actually
figure out (for the first time for me) how loops with GOTO jumps can be
translated to alternative structure. This turned out not to be too
hard. For a GOTO jump to a far outer group, one can use multiple breaks
at the end of each loop, possibly in addiction adding a else
clause to the different levels of the loops. (Python language can have
a else clause for for loops. It is executed when the loop
completes. (as opposed to when a break inside jumped out))

Here is a loop with GOTO, translated into Python without:

 N1: for my $aPair (@pairings) {
 for my $aGroup (@interm) {
 if (exists ${$aGroup}{$aPair-[0]})
{${$aGroup}{$aPair-[1]}='x'; next N1}
 if (exists ${$aGroup}{$aPair-[1]})
{${$aGroup}{$aPair-[0]}='x'; next N1}
 }
 push @interm, {$aPair-[0]='x'}; ${interm[-1]}{$aPair-[1]}='x';
 }
©---
©for aPair in pairings:
©for aGroup in interm:
©if (aGroup.has_key(aPair[0])): 

[ANN] Python 2.4 Quick Reference available

2005-02-19 Thread Richard Gruet
Hi Pythoners,

An updated version of the Python Quick Reference is available for Python 2.4
at http://rgruet.free.fr/#QuickRef.
It is a single looonnng html page (30 printed A4 pages) with a choice of 4
different CSS styles; also available in PDF.

Richard


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


Re: lambda closure question

2005-02-19 Thread jfj
Carl Banks wrote:
jfj wrote:
Carl Banks wrote:
Ted Lilley wrote:
Unfortunately, it doesn't work.  It seems the closure keeps track
of
the variable fed to it dynamically - if the variable changes after
[...]
At least, that's the explanation I'm deducing from this behavior.

And that's the correct explanation, chief.

It is intended that way.  As an example of why that is: consider a
nested function called printvars() that you could insert i
various
places within a function to print out the value of some local
variable.
If you did that, you wouldn't want printvars to print the values
at
the time it was bound, would you?
Allow me to disagree (and start a new confused with closures
thread:)
We know that python does not have references to variables. To some
newcomers this may seem annoying but eventually they understand the
pythonic way and they do without them. But in the case of closures
python supports references!

That's right.  It's called Practicality beats purity.
Yes, but according to the python philosophy one could pass locals()
to the nested function and grab the values from there. Seems practical
for the rareness of this...
 My experience bears this out: I find that about half the nested
functions I use are to reference an outer scope, half I return as a
closure.  Only once or twice did I try to use a nested function inside
the defining function.  I would guess this is more or less typical of
how nested functions are used.  If so, it was the right decision.
The question is how many of the nested functions you use take advantage
of the fact that the deref'd variable is a *reference to a variable* and
not a *constant* (different constant for each definition of the nested
function of course).
Or, IOW, it seems very reasonable that if somebody wants to write the
printvars() function, he could simply pass locals().
I would accept this being the right decision if there was a statement
like global var, called deref var with which nested funcs could
modify those variables.  Then we could say:
#
def foo():
def f1(y):
deref x
x = y
def f2():
print x
x=11
return f1, f2

But one should go with OOP in that case instead.
Ogligatory Python 3000 suggestion:
I hope in python 3000, we'll get rid of CellObjects and insert
freevars at the consts of the function object at MAKE_CLOSURE.
jfj
--
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] Python 2.4 Quick Reference available

2005-02-19 Thread Robin Becker
Richard Gruet wrote:
Hi Pythoners,
An updated version of the Python Quick Reference is available for Python 2.4
at http://rgruet.free.fr/#QuickRef.
It is a single looonnng html page (30 printed A4 pages) with a choice of 4
different CSS styles; also available in PDF.
Richard

Great news; thanks and thanks again
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list


Re: duplicate docstrings

2005-02-19 Thread Felix Wiemann
Steven Bethard wrote:

 class C(object):
  def foo(self):
  Foo things
  ...

 class D(object):
  def foo(self):
  Foo things
  ...

 It bothers me that I'm basically writing the same docstrings multiple
 times.  I guess what I really want to do is just write the docstrings
 for the interface I'm describing, and only supply docstrings in the
 classes when they need to differ from the interface docstrings.

 Is there a good way to do this?  If it's necessary, I can have C and D
 inherit from another class...

Use a common interface type and a metaclass which copies method
docstrings from base classes:

--
#!/usr/bin/env python

import inspect


class DocstringMetaclass(type):

Copy method docstrings.

def __init__(cls, *args):
super(DocstringMetaclass, cls).__init__(*args)
for name, method in cls.__dict__.iteritems():
# method is a function, not a method, so we use isfunction().
if not inspect.isfunction(method) or method.__doc__ is not None:
continue
for c in cls.mro():
if hasattr(c, name):
m = getattr(c, name)
if inspect.ismethod(m) and m.__doc__ is not None:
method.__doc__ = m.__doc__
break


class Interface(object):

__metaclass__ = DocstringMetaclass

def foo(self):
Foo things

def bar(self):
Bar things

def baz(self):
Baz things in a C manner


class Implementation(Interface):

def foo(self):
pass

def bar(self):
pass

def baz(self):
pass


print Implementation.foo.__doc__
print Implementation.bar.__doc__
print Implementation.baz.__doc__
--

Output:

Foo things
Bar things
Baz things in a C manner

-- 
Felix Wiemann -- http://www.ososo.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question on python 2.4 and tkinter

2005-02-19 Thread Raymond L. Buvel
David Joyner wrote:
Hi:
I'm trying to compile python 2.4 with tkinter.
(I'm trying to write a gui interface which
calls a program called GAP - I'm hoping to use
subprocess, a python 2.4 module, since I was getting
deadlocks using popen).
The instructions at the python web site said basically
to edit the /Modules/Setup file and recompile.
The edits consist of determining with location of various
Tcl/Tk libraries, header files, etc. I was wondering if
anyone could help out with how to determine these.
I have a suse 9.1 box and a new debian laptop, both of which
I would like to configure with python 2.4 and tkinter.
- David Joyner
The problem is most likely missing header files for the Tcl/Tk 
libraries.  Most Linux distributions (including SuSE) package the 
required files separately from the libraries.  In Yast, look for 
packages with the same name and a -dev suffix.  Once you have installed 
these, tkinter will be automatically built without any need to edit 
/Modules/Setup.

If you are running Debian testing or unstable, you just need to install 
the python2.4 and python2.4-tk modules.  If you need to compile 
extension modules, you will also need python2.4-dev.

Hope this helps.
Ray Buvel
--
http://mail.python.org/mailman/listinfo/python-list


[ANN] mlabwrap v0.9b3

2005-02-19 Thread Alexander Schmolck
I have recently uploaded mlabwrap v0.9b3, a high-level python to matlab(tm)
bridge, you can get it from

http://mlabwrap.sourceforge.net/

It should work with recent python =2.3 and matlab(tm) =6.0; I've used it
extensively myself but this is the first announcement to a wider public -- so
I'd very much like to hear some feedback (even if it's just works fine).

Here is a short demo snippet:

 from mlabwrap import mlab
 import Numeric
 mlab.lookfor('singular value')
GSVD   Generalized Singular Value Decompostion.
SVDSingular value decomposition.
[...]
 help(mlab.svd)
mlab_command(*args, **kwargs)
 SVDSingular value decomposition.
[U,S,V] = SVD(X) produces a diagonal matrix S, of the same
dimension as X and with nonnegative diagonal elements in
[...]
 mlab.svd(array([[1,2], [1,3]]))
array([[ 3.86432845],
  [ 0.25877718]])

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


Re: lambda closure question

2005-02-19 Thread Kent Johnson
Ted Lilley wrote:
What I want to do is pre-load functions with arguments by iterating
through a list like so:

class myclass:
...pass
def func(self, arg):
...print arg
mylist = [my, sample, list]
for item in mylist:
...setattr(myclass, item, lamdba self: func(self, item))
This attaches a list of functions to the class, making them bound
methods when called from a class instance.

obj = myclass()
obj.list()
list
Unfortunately, it doesn't work.  It seems the closure keeps track of
the variable fed to it dynamically - if the variable changes after the
lambda is created, the lambda still references the _variable_ not the
original _value_ and so gets the new value like so:

obj.sample()
list
obj.my()
list
The closure isn't bound until the scope containing it is exited. A simple workaround is to bind item 
as a default argument to the lambda:
for item in mylist:
setattr(myclass, item, lambda self, item=item: func(self, item))

You can also make a helper function that returns the closure, the closure will be bound each time 
the helper returns:

def make_f(item):
def f(self): func(self, item)
return f
mylist = [my, sample, list]
for item in mylist:
setattr(myclass, item, make_f(item))
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-19 Thread Ilias Lazaridis
Martin v. Löwis wrote:
Ilias Lazaridis wrote:
My questions:
It appears that nobody has answered the questions, yet.
a) Why does the Python Foundation not provide additionally a binary 
version, compiled with MinGW or another open-source compiler?
We don't have the resources to do that.
Should a professional developer take python serious?
I mean, if the team does not manage at least the foundation of a 
multi-target automated-build-process?

[targets need not to be supported directly by the python team. They 
could be added/managed/maintained by community members]

b) Why does the Python Foundation not ensure, that the python 
source-code is directly compilable with MinGW?
In the past, we did not do that because we did not know how to do it.
With Python 2.4.1, we now had a contribution that should allow direct
compilation of extensions using MingW.
I'm refering to compile the main python source-code with MigGW.
[As a result, compilation of extensions under MinGW becomes trivial]
c) Why are the following efforts not _directly_ included in the python 
source code base?

http://jove.prohosting.com/iwave/ipython/pyMinGW.html
I believe this was because it was never contributed to Python.
ok
You should possibly engourage the author to create an collaborative project.
d) Is it really neccessary that I dive into such adventures, to be 
able to do the most natural thing like: developing python extensions 
with MinGW?

http://starship.python.net/crew/kernr/mingw32/Notes.html
No. These instructions are outdated.
ok
[the author has placed a remark now, avoiding this way further 
missunderstandings.]

e) Is there any official statement available regarding the msvcr71.dll 
and other MS licensing issues?

[see several threads [Python-Dev] Is msvcr71.dll re-redistributable?]
http://mail.python.org/pipermail/python-dev/2005-February/thread.html
No, there isn't.
Seeing the discussions which raise around this topic, I think the 
foundation should provide an official statement [e.g. contact MS to get 
an official statement].

f) Are there any official (Python Foundation) statements / rationales 
available, which explain why the MinGW compiler is unsupported, 
although parts of the community obviously like to use it?

http://groups-beta.google.com/group/comp.lang.python/msg/dc3474e6c8053336
The official statement is that the MingW compiler is supported, indeed.
Thus the official statement should be possibly corrected.
 * Compiling Python source-code under MinGW is not directly supported.
 * Compliling extensions under MinGW leads possibly to problems.
Regards,
Martin
.
--
http://lazaridis.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-19 Thread Diez B. Roggisch
 Should a professional developer take python serious?

Unnecessary and deliberately provoking question - python is taken seriously,
e.g. by multi-billion dollar companies like google and zope. You OTH have
provided no evidence so far that you can be taken seriously as a developer
of whatever kind - neither professional nor hobbyist. So one has to
question the relevance of your demands.
 
 I mean, if the team does not manage at least the foundation of a
 multi-target automated-build-process?

Plain wrong. The team does very well manage that process - for a large
variety of platforms and compilers. Just not the compiler you perceive as
being a necessity. But that dead horse has been beaten enough already.


-- 
Regards,

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


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-19 Thread Diez B. Roggisch
 Unnecessary and deliberately provoking question - python is taken
 seriously, e.g. by multi-billion dollar companies like google and zope.

Of course zope corporation is not amongst the multi-billion dollar companies
- by now. But who knows :)

-- 
Regards,

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


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-19 Thread Ilias Lazaridis
Diez B. Roggisch wrote:
Should a professional developer take python serious?
[...] - (ungentle babbling after disrupting coherence of writings)

Should a professional developer take python serious?
I mean, if the team does not manage at least the foundation of a 
multi-target automated-build-process?

[targets need not to be supported directly by the python team. They 
could be added/managed/maintained by community members]


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


On eval and its substitution of globals

2005-02-19 Thread Paddy
Hi,
I got tripped up on the way eval works with respect to modules and
so wrote a test.

It seems that a function carries around knowledge of the globals()
present
when it was defined. (The .func_globals attribute)?

When evaluated using eval(...) the embedded globals can be overridden
with
the one passed through the eval(...) call

If however you create a new function that calls the first then eval's
global argument is only substituted in the outer call!

TEST:
=

Python 2.4 (#2, Jan  8 2005, 20:18:03)
[GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2
Type help, copyright, credits or license for more information.
 globals().has_key('A')
False
 globals().has_key('B')
False
 def f1(): return A  B
...
 def z(): return f1()
...
 eval(f1.func_code,dict(A=1,B=2))
True
 eval(z.func_code,dict(A=1,B=2, f1=f1))
Traceback (most recent call last):
  File stdin, line 1, in ?
  File stdin, line 1, in z
  File stdin, line 1, in f1
NameError: global name 'A' is not defined


ENDTEST
===

Is there a way to do a deep substitution of the globals?

I should add that f1 is given as-is. I can modify z,
and f1 is just one of many functions given and function z
is some boolean function of the fn's


Thanks, Pad.

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


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-19 Thread Diez B. Roggisch
Ilias Lazaridis wrote:

 Diez B. Roggisch wrote:
Should a professional developer take python serious?
 [...] - (ungentle babbling after disrupting coherence of writings)

And that from you *lol*

 I mean, if the team does not manage at least the foundation of a
 multi-target automated-build-process?

Repeating nonsense doesn't increase it's validity. Python makes use of
autoconf/automake to support a wide range of platforms and compilers. As
you obviously haven't heard of these and refuse to google, I was so kind to
research the respective links to the tools:

http://www.gnu.org/software/autoconf/
http://www.gnu.org/software/automake/

http://www.amath.washington.edu/~lf/tutorials/autoconf/

Enjoy the read.
 
 [targets need not to be supported directly by the python team. They
 could be added/managed/maintained by community members]

You already found the mingw-patch for building python. It is
added/managed/maintained by community members.

Just out of curiousity: How many python extensions are you planning to
write? And how many lines of pure python code have you written in your
life? 

-- 
Regards,

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


Re: [ANN] Python 2.4 Quick Reference available

2005-02-19 Thread Franz Steinhäusler
On Sat, 19 Feb 2005 13:00:59 +0100, Richard Gruet
[EMAIL PROTECTED] wrote:

Hi Pythoners,

An updated version of the Python Quick Reference is available for Python 2.4
at http://rgruet.free.fr/#QuickRef.
It is a single looonnng html page (30 printed A4 pages) with a choice of 4
different CSS styles; also available in PDF.

Richard


Hello Richard,

many thanks!

Such a coincidence, because I wanted to ask these
days, wheter a newer one exist (I have a printed reference for Python
1.5.1)



-- 
Franz Steinhäusler

DrPython (Project Developer) 
http://mitglied.lycos.de/drpython/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode encoding usablilty problem

2005-02-19 Thread Alexander Schremmer
On Fri, 18 Feb 2005 21:43:52 +0100, Thomas Heller wrote:

 Eventually, the primary string type should be the Unicode
 string. If you are curious how far we are still off that goal,
 just try running your program with the -U option.
 
 Not very far - can't even call functions ;-)
 
 def f(**kw):
 ...   pass
 ...
 f(**{a: 0})
 Traceback (most recent call last):
   File stdin, line 1, in ?
 TypeError: f() keywords must be strings

That is possible:
 f(**{chr(ord(a)): 0})


WFM. SCNR,
Alexander
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] Python 2.4 Quick Reference available

2005-02-19 Thread Pete Havens
The is awesome! Thanks. I did notice one thing while reading it. In the
File Object section, it states:

Created with built-in functions open() [preferred] or its alias
file().

...this seems to be the opposite of the Python documentation:

The file() constructor is new in Python 2.2. The previous spelling,
open(), is retained for compatibility, and is an alias for file().

...but I'm picking nits, because this is a fantastic piece of work and
will be very useful to me. Thanks again!

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


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-19 Thread Fredrik Lundh
Ilias Lazaridis wrote:

 Should a professional developer take python serious?

yes.

/F 



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


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-19 Thread Ilias Lazaridis
Diez B. Roggisch wrote:
Ilias Lazaridis wrote:
Diez B. Roggisch wrote:
Should a professional developer take python serious?
[...] - (ungentle babbling after disrupting coherence of writings)
And that from you *lol*
Of course.
I respect the coherence of writings of my conversation partners.
[If they are in-topic / in-context]
I mean, if the team does not manage at least the foundation of a
multi-target automated-build-process?
Repeating nonsense doesn't increase it's validity. Python makes use of
[...] - (babbling, gentle links)
Thank you for the links.
They are irrelevant for me.
But other readers for sure will enjoy.
-
The automated-build-process-system should allow community-members to add 
their targets into an special incubation section, which does not in 
any way affect the main section (which contains the official 
production targets).

If an incubation section target proves over time as stable and 
supported, it is moved to the official-auto-build.

[targets need not to be supported directly by the python team. They
could be added/managed/maintained by community members]
You already found the mingw-patch for building python. It is
added/managed/maintained by community members.
This is a one-man-show, which does not invite to open collaboration 
(feedback is requested to closed email):

http://groups-beta.google.com/group/comp.lang.python/msg/98fa42dabff68db2
python [foundation, crew, dictator, ...] should engourage open 
collaboration, should engourage _collaboration_.

Just out of curiousity: How many python extensions are you planning to
write? 
I estimate 10 to 100, depending on abstractional capabilities of the 
extension system.

And how many lines of pure python code have you written in your life? 
0 (zero).
.
--
http://lazaridis.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: unicode and socket

2005-02-19 Thread aurora
On 18 Feb 2005 19:10:36 -0800, [EMAIL PROTECTED] wrote:
It's really funny, I cannot send a unicode stream throuth socket with
python while all the other languages as perl,c and java can do it.
then, how about converting the unicode string to a binary stream? It is
possible to send a binary through socket with python?
I was answering your specific question:
How can I send the unicode string to the remote end of the socket as it  
is without any conversion of encode

The answer is you could not. Not that you cannot sent unicode but you have  
to encode it. The same applies to perl, c or Java. The only difference is  
the detail of how strings get encoded.

There are a few posts suggest various means. Or you can check out  
codecs.getwriter() which closer resembles Java's way.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Probably over my head... Trying to get Font Names

2005-02-19 Thread Samantha
Mike I did get the last msg. Still trying to get things under control.
S
Mike C. Fletcher [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Samantha wrote:

Mike,
Not sure why that email bounced.

 That last one bounced too, btw.

I downloaded these files:
WinTTX2.0b1.exe
TTFQuery-1.0.0.win32.exe
numarray-1.1.1.win32-py2.4.exe

They all seemed to install. Is WinTTX2.0b1.exe not the fontTools file?

 I believe WinTTX is a font-editing program from which fontTools was split 
 out into a separate project.

 As well, though I don't *know* that this will cause problems, I'd thought 
 fontTools required Numeric (Numpy) rather than Numarray.  Would try the 
 fontTools package first with the Numarray you've installed, and if you 
 then find problems with it not being able to find Numeric, install the 
 Numpy release.

 HTH,
 Mike

 
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://www.vrplumber.com
  http://blog.vrplumber.com
  PyCon is coming...
 


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


Re: [perl-python] exercise: partition a list by equivalence

2005-02-19 Thread Reinhold Birkenfeld
Xah Lee wrote:
 here's the answer to the partition by equivalence exercise.

Your Python solution is, as expected, wrong (try with
[[10, 8], [7, 3], [1, 7], [5, 4], [2, 2], [3, 8], [7, 10], [2, 3], [6,
10], [3, 2]]
for example).

The solution by John Lenton is wrong, too.

The solution by Brian Beck delivers the correct result for most input,
but for some input lists like
[[3, 3], [8, 7], [3, 2], [8, 5], [5, 6], [6, 3], [10, 8], [8, 10], [4,
10], [10, 2]]
it chokes and returns the empty list.

My solution (which may not be the fastest or most effective, but till
now is the shortest wink and it works):

def merge(pairings):
sets = {}
for x1, x2 in pairings:
newset = (sets.get(x1, frozenset([x1]))
  | sets.get(x2, frozenset([x2])))
for i in newset:
sets[i] = newset

return [list(aset) for aset in set(sets.itervalues())]


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


wxPython 2.5 - bug in wx.Execute

2005-02-19 Thread Andy Leszczynski
Hi,
I need a help with following problem which is blocking me quite seriously.
I noted some weird behavior on Windows (Python 2.3, wxPython 2.5). The 
same code works fine under Linux.

When using pid = wx.Execute(cmd, wx.EXEC_ASYNC, self.process) to spawn 
new wxPython based GUI program, the GUI does not pop up. I checked that 
the process itself is running/alive, the print over the streams get 
propagated to the parent process, but no GUI. It only happnes for 
wxPython based programs - for e.g. regural python command line programs 
it works fine.

It is easy to be replicated using wx Demo by opening Process and 
Events/Process.  Then after typing in python -u demo.py  nothing happens.

Please help, it really blocks me.  The temporary work around is to use 
cmd /e python -u demo.py, but I lose the unbuffered -u effect.

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


Re: unicode and socket

2005-02-19 Thread Fredrik Lundh
anonymous coward [EMAIL PROTECTED] wrote:

 It's really funny, I cannot send a unicode stream throuth socket with
 python while all the other languages as perl,c and java can do it.

Are you sure you understand what Unicode is, and how sockets work?

Sockets are used to transfer byte streams.  If you want to transfer
a python-level object, you have to decide how to encode it as a
byte stream.  For integers, you have to decide whether to use a single
byte, a string of decimal ascii characters, netstring syntax, etc.  For
text, you have to decide what character encoding to use.  For arbitrary
objects, you have to decide what serialisation protocol to use.  etc.

(and yes, the same applies to all other languages.  Java sockets and C
sockets are no different from Python sockets...)

/F 



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


could that be a mutable object issue ?

2005-02-19 Thread Philippe C. Martin
If I do this:



print 'LEN OF BOOK BEFORE APPEND: ', len(pickle.dumps(self.__m_rw))
self.__m_rw.books.append( [p_col1,p_col2,p_col3] )
print 'LEN OF BOOK AFTER APPEND: ', len(pickle.dumps(self.__m_rw))

I get the same length before and after append.

when I print self.__m_rw.books, I see my 'appends' in there, yet the
pickled object does not change.

Any clue ?

Thanks


Philippe



-- 
***
Philippe C. Martin
SnakeCard LLC
www.snakecard.com
***

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


Re: could that be a mutable object issue ?

2005-02-19 Thread Fredrik Lundh
Philippe C. Martin wrote:

 print 'LEN OF BOOK BEFORE APPEND: ', len(pickle.dumps(self.__m_rw))
 self.__m_rw.books.append( [p_col1,p_col2,p_col3] )
 print 'LEN OF BOOK AFTER APPEND: ', len(pickle.dumps(self.__m_rw))

 I get the same length before and after append.

 when I print self.__m_rw.books, I see my 'appends' in there, yet the
 pickled object does not change.

instead of checking the length, have you checked what

pickle.loads(pickle.dumps(self.__m_rw))

returns?

/F 



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


Re: lambda closure question

2005-02-19 Thread Steven Bethard
Carl Banks wrote:
You may not be aware of it, but what you're trying to do is called
currying; you might want to search the Python Cookbook for recipes on
it.
Or look for partial function application which has been argued to be 
the correct term for this use...  Also see PEP 309:

http://www.python.org/peps/pep-0309.html
With an appropriately defined partial (I've taken the one from the PEP 
and added the descriptor machinery necessary to make it work as an 
instancemethod):

 functional.py 
class partial(object):
def __init__(*args, **kwargs):
self = args[0]
try:
self.fn = args[1]
except IndexError:
raise TypeError('expected 2 or more arguments, got ' %
len(args))
self.args = args[2:]
self.kwargs = kwargs
def __call__(self, *args, **kwargs):
if kwargs and self.kwargs:
d = self.kwargs.copy()
d.update(kwargs)
else:
d = kwargs or self.kwargs
return self.fn(*(self.args + args), **d)
def __get__(self, obj, type=None):
if obj is None:
return self
return partial(self, obj)
---
py class C(object):
... pass
...
py def func(self, arg):
... return arg
...
py lst = ['a', 'b', 'c']
py for item in lst:
... setattr(C, item, functional.partial(func, arg=item))
...
py c = C()
py c.a(), c.b(), c.c()
('a', 'b', 'c')
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: could that be a mutable object issue ?

2005-02-19 Thread Philippe C. Martin
Yes, and that is my initial problem: I seem to write correctly that
'pickle string' to a device, by when I read it back, the appended
information is gone.


On Sat, 19 Feb 2005 19:13:58 +0100, Fredrik Lundh wrote:

 Philippe C. Martin wrote:
 
 print 'LEN OF BOOK BEFORE APPEND: ', len(pickle.dumps(self.__m_rw))
 self.__m_rw.books.append( [p_col1,p_col2,p_col3] )
 print 'LEN OF BOOK AFTER APPEND: ', len(pickle.dumps(self.__m_rw))

 I get the same length before and after append.

 when I print self.__m_rw.books, I see my 'appends' in there, yet the
 pickled object does not change.
 
 instead of checking the length, have you checked what
 
 pickle.loads(pickle.dumps(self.__m_rw))
 
 returns?
 
 /F

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


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-19 Thread Diez B. Roggisch
 Thank you for the links.
 
 They are irrelevant for me.

As usual. 

 Just out of curiousity: How many python extensions are you planning to
 write?
 
 I estimate 10 to 100, depending on abstractional capabilities of the
 extension system.
 
 And how many lines of pure python code have you written in your life?
 
 0 (zero).

Awesome. Without any lines of code written, you have already identified the
areas where python lacks features that have to be overcome with C-written
extensions. As usual, I stand with my mouth agape over your near-psychic
abilities to analyze even the complexest matters without any actual
fiddling with the nitty gritty details. 

The day where you team up with Uri Geller - who will make even the worst
code running by just putting a printout of it on top of an image of the
master himself - is to be feared by all of us humble developers who
actually _deal_ with problems.

-- 
Regards,

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


Re: exercise: partition a list by equivalence

2005-02-19 Thread bearophileHUGS
David Eppstein:
 However it might be easier to treat the input pairs as the edges of a
 graph and apply a depth-first-search based graph connected components
 algorithm. || This would be O(n), though.

Is the DFS the best one here (instead of BFS)?

With the graph implementation that I've just shown here it becomes:

. import graph
. def merge(l):
. g = graph.Graph()
. g.addArcs(l)
. return g.connectedComponents()
. print merge( [ [1,2], [2,4], [5,6] ] )

I presume the complexity is O(n+a); n (the nodes) is proportional to
the number of pairs, and
a (the arcs) depends on the intricacy of the input pairs. For a
complete graph, this can
become slow (but there is a high probably that all the pairs are in the
same connected component).
Bye,
Bearophile

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


Re: exercise: partition a list by equivalence

2005-02-19 Thread bearophileHUGS
Bearophile:
 I presume the complexity is O(n+a); n (the nodes)
 is proportional to the number of pairs, and a
 (the arcs) depends on the intricacy of the input pairs.

Opps... n (the number of nodes) is the number of different numbers
contained in the pairs :-]

Bearophile

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


Re: [EVALUATION] - E02 - Support for MinGW Open Source Compiler

2005-02-19 Thread Ilias Lazaridis
Diez B. Roggisch wrote:
Thank you for the links.
They are irrelevant for me.
As usual. 
sorry.
Just out of curiousity: How many python extensions are you planning to
write?
I estimate 10 to 100, depending on abstractional capabilities of the
extension system.
And how many lines of pure python code have you written in your life?
0 (zero).
Awesome. Without any lines of code written, you have already identified the
areas where python lacks features that have to be overcome with C-written
extensions. 
writing code is not the only way.
As usual, I stand with my mouth agape over your near-psychic
abilities to analyze even the complexest matters without any actual
fiddling with the nitty gritty details. 
Nothing special.
Abstraction, Generalization, Inhibition.
The day where you team up with Uri Geller - who will make even the worst
code running by just putting a printout of it on top of an image of the
master himself - is to be feared by all of us humble developers who
actually _deal_ with problems.
Don't worry.
Mr. Geller will be shortly hired by Sun Microsystems.
.
--
http://lazaridis.com
--
http://mail.python.org/mailman/listinfo/python-list


pyWrath project

2005-02-19 Thread [EMAIL PROTECTED]
Privet!

I am bifacial, admin of the pywrath project
(http://sourcefoge.net/projects/pywrath). PyWrath is PBeM game/emgine
for python, based on principles of futuristic warfare.

PyWrath is still in very early fase of development, and we are in
constant need of developers. We are accepting each and every
man/woman/elf/alien/cyborg/whatelse who is capable to do some basic
(sometimes advanced) Python tasks.

Interested? Contact me at [EMAIL PROTECTED] or
[EMAIL PROTECTED]

Regards,
BiFacial

P. S. Sorry for crappy English. I am Russian, after all :)

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


Re: Pausing a program - poll/sleep/threads?

2005-02-19 Thread Simon John
OK, I've implemented the 2sec threaded update, but I'm having some
problems with it.

Basically the thread will have to just run constantly, never exiting
(just sleeping for 2secs), which seems to work OK except when I try to
get the thread to do anything with the main program's window.

As the thread doesn't end, it doesn't return a result, so on every pass
of the thread's while loop, I write the current track info to the
mainWindow directly, however this causes the program to hang. Here is a
snippet of the current method:

class ThreadedInfo(Thread):
overloads init and defines run
def __init__(self):
Thread.__init__(self)

def run(self):
# runs the whole time
while 1:
self.info()
time.sleep(2)

def info(self):
referencing window kills linux here

# get track info, returned as dictionary
self.info_dict = backend.getInfo(config.server, config.port)

I was thinking of getting the thread to just run once, then getting the
main program to write the result (using join() ) to the mainWindow.
That method would be something like this, but it's almost totally
pointless using a thread then, as the while loop will singletask the
program:

while 1:
# start thread
self.infothread.start()

# when thread ends, get result
self.result = self.infothread.join()

# write result to window
window.mainTextarea.setText(self.result)

# pause for 2secs before starting again
sleep(2)

I made sure that I built PyQt using threads, so that's not the issue.
Any other ideas?

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


Re: [ANN] Python 2.4 Quick Reference available

2005-02-19 Thread David M. Cooke
Pete Havens [EMAIL PROTECTED] writes:

 The is awesome! Thanks. I did notice one thing while reading it. In the
 File Object section, it states:

 Created with built-in functions open() [preferred] or its alias
 file().

 ...this seems to be the opposite of the Python documentation:

 The file() constructor is new in Python 2.2. The previous spelling,
 open(), is retained for compatibility, and is an alias for file().

Except if you look at the current development docs
(http://www.python.org/dev/doc/devel/lib/built-in-funcs.html) it says


The file() constructor is new in Python 2.2 and is an alias for
open(). Both spellings are equivalent. The intent is for open() to
continue to be preferred for use as a factory function which returns a
new file object. The spelling, file is more suited to type testing
(for example, writing isinstance(f, file)).


... which more accurately reflects what I believe the consensus is
about the usage of open vs. file.

-- 
||\/|
/--\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: exercise: partition a list by equivalence

2005-02-19 Thread David Eppstein
In article [EMAIL PROTECTED],
 [EMAIL PROTECTED] wrote:

 David Eppstein:
  However it might be easier to treat the input pairs as the edges of a
  graph and apply a depth-first-search based graph connected components
  algorithm. || This would be O(n), though.
 
 Is the DFS the best one here (instead of BFS)?

I'm not sure it makes much difference.

 With the graph implementation that I've just shown here it becomes:
 
 . import graph
 . def merge(l):
 . g = graph.Graph()
 . g.addArcs(l)
 . return g.connectedComponents()
 . print merge( [ [1,2], [2,4], [5,6] ] )
 
 I presume the complexity is O(n+a); n (the nodes) is proportional to
 the number of pairs, and
 a (the arcs) depends on the intricacy of the input pairs. For a
 complete graph, this can
 become slow (but there is a high probably that all the pairs are in the
 same connected component).

It's still linear in the input size, which is the best you could hope 
for.

-- 
David Eppstein
Computer Science Dept., Univ. of California, Irvine
http://www.ics.uci.edu/~eppstein/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: - E02 - Support for MinGW Open Source Compiler

2005-02-19 Thread A.B., Khalid
Ilias Lazaridis wrote:
 A.B., Khalid wrote:
  Ilias Lazaridis wrote:
 
 The first step is to make a pyMinGW project.
 
  You are mistaken. The first steps are the following:
 [...] - (nonrelevant comments)

  3) Realizing that there _is_ already a project called pyMinGW! That
it
  does not fit your requirements-- whatever these maybe-- is an
  altogether different issue. The fact of the matter remains that a
  project _does_ exist, one which people (including myself) do in
fact
  use; and because it does exist there is no reason to make it.
 [...]

 I've already understood your viewpoint.


You just say that you do. Your repeating the same arguments using the
same logic testifies that you don't.



 My requirements about an open-source project (or sub-project) are
very
 simple:


Your requirements are just what they are, _your_ requirements. And
since they are so, maybe you'd like to address them yourself instead of
continuing to complain how your requirements (simple or otherwise)
are not being met and that hence the author of this project is this,
and/or the entire language is that. Enough said here.


 You have the right to refuse this.

 I (and any other reader) have the right to derive our conclusions
about
 you and the reasons that you refuse a _real_ collaborative work.


Of course I have the right to do what I like (and as regards pyMinGW
this was explained earlier in this thread); your mere pronunciation
that I have that right neither subtracts nor adds to it one iota. And
it seems to me that the community has indeed reached some conclusions
which any reasonable person with a fair grasp of English can quickly
identify from the nature of their responses to you, here and elsewhere.


  You already found the mingw-patch for building python. It is
  added/managed/maintained by community members.

 This is a one-man-show, which does not invite to open collaboration
 (feedback is requested to closed email):


http://groups-beta.google.com/group/comp.lang.python/msg/98fa42dabff68db2

 python [foundation, crew, dictator, ...] should engourage open
 collaboration, should engourage _collaboration_.


Oh well, I hope it would not come as a shock to you that pyMinGW does
allow collaboration. Here is a quote from the pyMinGW-24 changes
document:

-
pyMinGW-24-0064: Dec 11th, 2004
-
[1] Included \PC\pyconfig.h in the Python24.iss. Thanks to Matthias
Gondan for the report and the fix.
Quoted from http://jove.prohosting.com/iwave/ipython/pyMinGW-24.html


So you see, the collaborative effort is there. It is just not
responding to your requirements to your liking that is bothering you!
Now if you want to continue complaining about how your requirements
are not being met, by volunteers who make their work available for free
in their spare time, to your liking, go ahead. Knock yourself out.


Khalid



--
pyMinGW:
http://jove.prohosting.com/iwave/ipython/pyMinGW.html

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


Re: Pausing a program - poll/sleep/threads?

2005-02-19 Thread Jarek Zgoda
Simon John napisa(a):
Damn, seems Qt GUI objects (windgets) aren't thread-safe:
http://doc.trolltech.com/3.3/threads.html#11
Like most (if not all) others GUI toolkits.
So I'm going to have to find a way of using a thread to fetch the data,
and then using the main program to update the GUI... Someone suggested
using events:
http://mail.python.org/pipermail/python-list/2002-February/089360.html
See http://www.informit.com/articles/printerfriendly.asp?p=30708
--
Jarek Zgoda
http://jpa.berlios.de/ | http://www.zgodowie.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: could that be a mutable object issue ?

2005-02-19 Thread Kent Johnson
Philippe C. Martin wrote:
If I do this:

print 'LEN OF BOOK BEFORE APPEND: ', len(pickle.dumps(self.__m_rw))
self.__m_rw.books.append( [p_col1,p_col2,p_col3] )
print 'LEN OF BOOK AFTER APPEND: ', len(pickle.dumps(self.__m_rw))
I get the same length before and after append.
when I print self.__m_rw.books, I see my 'appends' in there, yet the
pickled object does not change.
How is __m_rw.books defined? If it is a class attribute of the class of __m_rw you will see this 
behavior. e.g.

  class Mrw:
 ...   books = []
 ...
  m=Mrw()
  class Mrw:
 ...   books = []
 ...
  __m_rw = Mrw()
  __m_rw.books.append(1)
  __m_rw.books
[1]
but __m_rw.books will not be pickled with __m_rw because it belongs to the 
class, not the instance.
The fix is to declare books as an instance attribute:
class Mrw:
  def __init__(self):
self.books = []
Kent
Any clue ?
Thanks
Philippe

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


Re: - E02 - Support for MinGW Open Source Compiler

2005-02-19 Thread Pat
Diez B. Roggisch wrote:

  Just out of curiousity: How many python extensions are you
planning to
  write?
 
  I estimate 10 to 100, depending on abstractional capabilities of
the
  extension system.
 
  And how many lines of pure python code have you written in your
life?
 
  0 (zero).

 Awesome. Without any lines of code written, you have already
identified the
 areas where python lacks features that have to be overcome with
C-written
 extensions. As usual, I stand with my mouth agape over your
near-psychic
 abilities to analyze even the complexest matters without any actual
 fiddling with the nitty gritty details.

If you put yourself into the shoes of someone who decides to use a
Python product that requires compiling, and that product contains C
extensions that also need compiling, you'll see that it doesn't matter
whether or not that individual has actually written a single line of
Python themselves.  If the compiling process is not easy, then that
user will be forced to fiddle with nitty gritty details about which
they'd rather remain ignorant.

On Linux, I've installed and used/compiled products in a variety of
languages in which I've never written a single line of source code
myself.  In most cases the process works fairly well.  When it doesn't,
I'm forced to fiddle with nitty gritty details about which I'd rather
remain ignorant.  The result is usually a good deal of frustration and
anger on my part.

On Windows, most users are used to installing precompiled binary
packages, rather than compiling from source.  When you do have to
compile from source, it often requires you to fiddle with nitty gritty
details about which you'd rather remain ignorant.  The less fiddling
required, the happier the user will be, and the easier it will be for
that product to get adopted on that platform.  No psychic abilities are
required.  No Python abilities are required, either, for that matter.
;-)

--
Patrick K. O'Brien
Orbtechhttp://www.orbtech.com
Schevo http://www.schevo.org
Pypersyst  http://www.pypersyst.org

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


controlling a qbasic program on a windows98 or example of rs-232 commanded through python

2005-02-19 Thread [EMAIL PROTECTED]
Hello,

Can python be installed on a win98 system ? if so, how do I control a
qbasic program from python ?

the qbasic program controls input to an RS-232 so I am enclined to
follow the win98 system + qbasic route in order to be quick, or I guess
the question could be, can I control a device through rs-232 from a
newer version of windows using python (actually for the last part of
the question I know this is feasible, but I 'd like to see an example,
any pointers ?)

Thanks for any insight,

Jake.

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


PIL Expand Canvas

2005-02-19 Thread Daniel Bowett
I'm new to the PIL module but think it would be useful for dealing with 
all the product images for the sites I work on. I can see how to do most 
things I need apart from expanding the canvas.

By that I mean if I have an image which is 200 pixels high and 180 
pixels wide - I will want to pad it left and right by 10 pixels with 
white space to make it a 200x200 square.

Is this possible?
--
http://mail.python.org/mailman/listinfo/python-list


Re: [perl-python] exercise: partition a list by equivalence

2005-02-19 Thread Brian Beck
Reinhold Birkenfeld wrote:
def merge(pairings):
sets = {}
for x1, x2 in pairings:
newset = (sets.get(x1, frozenset([x1]))
  | sets.get(x2, frozenset([x2])))
for i in newset:
sets[i] = newset
return [list(aset) for aset in set(sets.itervalues())]
Looks good. I used it as inspiration for this new one, which takes less 
time for large datasets, and especially for those where a good number of 
merges are expected (at least that looks to be the pattern; with some 
large datasets this takes less than a quarter of the time as the one 
above). I'm sure it can be improved still -- yours is still faster in 
many cases.

def merge2(pairings):
elements = {}
sets = []
for x1, x2 in pairings:
i = [elements.get(x1, -1), elements.get(x2, -1)]
i.sort()
if i[1] == -1:
i[1] = len(sets)
sets.append(set([x1, x2]))
elif i[0] == -1:
sets[i[1]] |= set([x1, x2])
elif i[0] == i[1]:
continue
else:
sets[i[1]] |= sets[i[0]]
sets[i[0]].clear()
for x in sets[i[1]]:
   elements[x] = i[1]
return [list(s) for s in sets if s]
# Comparison
import profile
import random
# Play with these values
xMax, nPairs = 1000, 5000
l = [[random.randint(0, xMax), random.randint(0, xMax)] for i in 
range(nPairs)]

print 'merge2:'
profile.run('merge2(l)') # Mine
print 'merge:'
profile.run('merge(l)') # Reinhold's
--
Brian Beck
Adventurer of the First Order
--
http://mail.python.org/mailman/listinfo/python-list


Distutils: relative paths

2005-02-19 Thread Frans Englich

Hello,

I have trouble installing a data directory which is not a child of my package 
directory in the source directory.

My source directory looks like this:

./setup.py
schemas/*.xsd
foo/*.py

And when it's installed, it should look like:

site-packages/foo/*.py
site-packages/foo/schemas/*.xsd

In other words, schemas, from being a sibling of foo, became a child of foo.

Now, how is this expressed in the setup.py?

I tried this:

setup( name=Foo,
packages=[foo],
package_data={ foo: [../schemas/*.xsd] },
package_dir={ foo: foo},
[...]

but it resulted in schemas being a package, not child of foo(!). 

I've read the relevant page in the reference manual, 
http://www.python.org/doc/current/dist/node11.html

but I can't find the trick. Any ideas?


Cheers,

Frans

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


Creditwrench

2005-02-19 Thread Creditwrench
And the truth shall set ye free

http://www.creditwrench-thetruth.blogspot.com/

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


socket or xml error?

2005-02-19 Thread [EMAIL PROTECTED]
I got an error as following.  The Server/cllient program was written by
somebody else and supposed to be working before.  Whenever I start a
new client to load xml data from server, the program will fail as:


 File ShowAllData.py, line 157, in ?
main(sys.argv)
  File ShowAllData.py, line 130, in main
win = MainWindow()
  File ShowAllData.py, line 63, in __init__
videoInfo =
CaMLDocumentParser.getVideoInfo(GenericParser.parse(StringIO(result)))
  File /home/vraid1/mzhang/CaMLServer3/lib/GenericParser.py, line 39,
in parse
xml.sax.parse (file, g)
  File /usr/lib/python2.2/site-packages/_xmlplus/sax/__init__.py,
line 31, in parse
parser.parse(filename_or_stream)
  File /usr/lib/python2.2/site-packages/_xmlplus/sax/expatreader.py,
line 109, in parse
xmlreader.IncrementalParser.parse(self, source)
  File /usr/lib/python2.2/site-packages/_xmlplus/sax/xmlreader.py,
line 123, in parse
self.feed(buffer)
  File /usr/lib/python2.2/site-packages/_xmlplus/sax/expatreader.py,
line 220, in feed
self._err_handler.fatalError(exc)
  File /usr/lib/python2.2/site-packages/_xmlplus/sax/handler.py, line
38, in fatalError
raise exception
xml.sax._exceptions.SAXParseException: unknown:1:0: not well-formed
(invalid token

Any ideas?

Thanks

Michael

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


Re: exercise: partition a list by equivalence

2005-02-19 Thread John Machin

Reinhold Birkenfeld wrote:
 Xah Lee wrote:
  here's the answer to the partition by equivalence exercise.

 Your Python solution is, as expected, wrong (try with
 [[10, 8], [7, 3], [1, 7], [5, 4], [2, 2], [3, 8], [7, 10], [2, 3],
[6,
 10], [3, 2]]
 for example).

 The solution by John Lenton is wrong, too.

 The solution by Brian Beck delivers the correct result for most
input,
 but for some input lists like
 [[3, 3], [8, 7], [3, 2], [8, 5], [5, 6], [6, 3], [10, 8], [8, 10],
[4,
 10], [10, 2]]
 it chokes and returns the empty list.

 My solution (which may not be the fastest or most effective, but till
 now is the shortest wink and it works):

 def merge(pairings):
 sets = {}
 for x1, x2 in pairings:
 newset = (sets.get(x1, frozenset([x1]))
   | sets.get(x2, frozenset([x2])))
 for i in newset:
 sets[i] = newset

 return [list(aset) for aset in set(sets.itervalues())]


 Reinhold

FWIW, here's a brief UAT report:

Appears to work: Reinhold, David, Xah (v2)
Has bug(s): John L (v*), Brian (v*)
Incomprehensible: Xah (v*)

'Come back after lunch' award goes to Xah v2, which at a glance appears
to be O(N**4) -- dictionary.update() inside 3-deep nest of 'for'
statements.

Here's a small input that busts all non-working versions:

input: [[1, 2], [3, 4], [2, 3], [4, 5]]
merge_RB  - [[1, 2, 3, 4, 5]]
merge_DE  - [[1, 2, 3, 4, 5]]
merge_JL  - [[1, 2, 3, 4], [5]]
merge_JL2 - [[1, 2, 3, 4], [5]]
merge_BB  - []
merge_XL  - [[1, 2, 3, 4, 5], [3, 4, 5]]
merge_XL2 - [[1, 2, 3, 4, 5]]

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


Re: Annoying Socket Problem

2005-02-19 Thread John Abel
Never mind, sorted now.
On 18 Feb 2005, at 15:10, John Abel wrote:
Read/tried that before posting.  Even with a flush, everything hangs  
until I kill the client.

Irmen de Jong wrote:
John Abel wrote:
I'm hoping this is something simple, and someone can point me in the  
right direction here.  I have a class based on SocketServer  
(ThreadingTCPServer), and I've used makefile on the socket so I use  
the for in  routine.  My client sends it a small amount of data.   
However, both programs appear to hang once the data has been sent,  
obviously something to do with flushing.

http://www.amk.ca/python/howto/sockets/ 
sockets.html#SECTION00040

--Irmen

--
*John Abel
Senior Unix Administrator*
PA News Limited
www.pa.press.net http://www.pa.press.net
E-Mail address: [EMAIL PROTECTED] mailto:[EMAIL PROTECTED]
Telephone Number : 01430 43
Fax Number : 0870 1240192
Mobile Number : 07971 611356
The Bishop's Manor, Market Place, Howden, DN14 7BL
PA News Limited, 292 Vauxhall Bridge Road, London SW1V 1AE. Registered  
in England No. 3891053.
--
http://mail.python.org/mailman/listinfo/python-list

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


Re: could that be a mutable object issue ?

2005-02-19 Thread Philippe C. Martin
You are correct and I still don't know Python (sigh).

Thanks

Philippe


On Sat, 19 Feb 2005 15:51:18 -0500, Kent Johnson wrote:

 Philippe C. Martin wrote:
 If I do this:
 
 
 
 print 'LEN OF BOOK BEFORE APPEND: ', len(pickle.dumps(self.__m_rw))
 self.__m_rw.books.append( [p_col1,p_col2,p_col3] )
 print 'LEN OF BOOK AFTER APPEND: ', len(pickle.dumps(self.__m_rw))
 
 I get the same length before and after append.
 
 when I print self.__m_rw.books, I see my 'appends' in there, yet the
 pickled object does not change.
 
 How is __m_rw.books defined? If it is a class attribute of the class of 
 __m_rw you will see this 
 behavior. e.g.
 
class Mrw:
   ...   books = []
   ...
m=Mrw()
class Mrw:
   ...   books = []
   ...
__m_rw = Mrw()
__m_rw.books.append(1)
__m_rw.books
 [1]
 
 but __m_rw.books will not be pickled with __m_rw because it belongs to the 
 class, not the instance.
 
 The fix is to declare books as an instance attribute:
 
 class Mrw:
def __init__(self):
  self.books = []
 
 Kent
 
 
 Any clue ?
 
 Thanks
 
 
 Philippe
 
 


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


Re: PIL Expand Canvas

2005-02-19 Thread Will McGugan
Daniel Bowett wrote:
I'm new to the PIL module but think it would be useful for dealing with 
all the product images for the sites I work on. I can see how to do most 
things I need apart from expanding the canvas.

By that I mean if I have an image which is 200 pixels high and 180 
pixels wide - I will want to pad it left and right by 10 pixels with 
white space to make it a 200x200 square.

Is this possible?
You could create a new canvas of the larger dimensions, then copy the 
smaller one to the centre of it..

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


Error when display socekt content

2005-02-19 Thread [EMAIL PROTECTED]
Hello all,

The displayed string looks like some wierd chars (unreadable to human
being at all), when I tried to display the received message by socket.
I read by this line:
  body = self.io.blockingRead (int(header.getFieldCN
('Content-Length')))
  print socket content:  + body

I am new to python, could you tell me where I did wrong?

Thank you,

Michael

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


Re: Distutils: relative paths

2005-02-19 Thread George Sakkis

Frans Englich [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]

 Hello,

 I have trouble installing a data directory which is not a child of my package
 directory in the source directory.

 My source directory looks like this:

 ./setup.py
 schemas/*.xsd
 foo/*.py

 And when it's installed, it should look like:

 site-packages/foo/*.py
 site-packages/foo/schemas/*.xsd

 In other words, schemas, from being a sibling of foo, became a child of foo.

 Now, how is this expressed in the setup.py?

 I tried this:

 setup( name=Foo,
 packages=[foo],
 package_data={ foo: [../schemas/*.xsd] },
 package_dir={ foo: foo},
 [...]

 but it resulted in schemas being a package, not child of foo(!).

 I've read the relevant page in the reference manual,
 http://www.python.org/doc/current/dist/node11.html

 but I can't find the trick. Any ideas?


 Cheers,

 Frans


If I interpret it correctly, the files are expected to be part of the package 
in the source
directories means that you cannot specify a sibling directory as package data, 
so the easiest way
is to make schemas child of foo. If this is not possible, you may check the 
'data_files' option
(http://www.python.org/doc/current/dist/node12.html).

George


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


segfault when calling Python from C thread

2005-02-19 Thread Travis Berg

I'm running into a problem when trying to perform a callback to a Python
function from a C extension.  Specifically, the callback is being made by
a pthread that seems to cause the problem.  If I call the callback from
the parent process, it works fine.  The PyObject is static, and holds the
same value in both Parent and thread, so I'm at a loss as to what would be
different in the pthread from the parent that would cause a segfault on
the callback.  The machine specifics are an x86 intel processor with
RedHat linux.

Here is some clips of the C callback code showing how I'm storing the
callback, then what the actual callback function is like.  Any ideas?
The function being called is a simply to display the string of text, and
execution never seems to reach back to the Python code at all.

Thanks,
Travis B.


/* callback function to the Python code */
static PyObject * my_callback = NULL;

/* setting callback function */
static PyObject * my_set_callback(PyObject *dummy, PyObject *args)
{
PyObject *result = NULL;
PyObject *temp;
PyObject *arglist;

if (PyArg_ParseTuple(args, O:set_callback, temp)) {
if (!PyCallable_Check(temp)) {
PyErr_SetString(PyExc_TypeError,
parameter must be callable);
return NULL;
}
Py_XINCREF(temp); /* Add a reference to new callback */
Py_XDECREF(my_callback);  /* Dispose of previous callback */
my_callback = temp;   /* Remember new callback */
/* return None */
Py_INCREF(Py_None);
result = Py_None;
}
return result;
}

/* calling callback */
void callback(char * str) {
PyObject *arglist;
PyObject *result;
if(str == NULL)
return;

if(my_callback == NULL) {
printf(no callback function provided, returning...\n);
return;
}

/* Time to call the callback */
arglist = Py_BuildValue((s), str);
result = PyEval_CallObject(my_callback, arglist);
Py_DECREF(arglist);
if(result == NULL)
return;
Py_DECREF(result);
}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Error when display socekt content

2005-02-19 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
The displayed string looks like some wierd chars (unreadable to human
being at all), when I tried to display the received message by socket.
I read by this line:
  body = self.io.blockingRead (int(header.getFieldCN
('Content-Length')))
  print socket content:  + body
I am new to python, could you tell me where I did wrong?
You didn't post enough information for anyone to help much, that's
what...
Most importantly, what did you *expect* the above to do?  For
all I can tell, you should have expected it to print
socket content:  followed by some potentially unreadable
data, which is what you got...
Also, it will help if you describe what self.io is, what
header.getFieldCN is, and what kind of communications protocol
is involved in what you're doing.  And, if it's HTTP as it
appears it might be, perhaps explain why you aren't using
something simple like urllib2 to deal with it...
Mentioning what platform (versions of OS and Python) you
are using is always a good idea too.
Cutting and pasting the *actual* output, or something
that describes a little better what you actually got and
what you expected to get is also a good idea... give us
enough information to help you and you'll be helping yourself.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Fuzzy matching of postal addresses

2005-02-19 Thread McBooCzech
Sorry for my Ferbl typo. For the local anti-smoking campaign I am
trying to link some addresses which contain following linkable
informations (data fields) only:

RECORD_ID, Street + No., City, Post code,

All data are now w/o Unicode characters. Do you think it possible to
try to link it with Febrl w/o deep code modification?

I did try to link our data but the result is just a plenty of warning
messages but no links. What is your suggestion? Please understand I do
not want to bother you with my questions. I am just asking you your
comments or pointers before I will try to dig in to the code. You
probably know some tricks in data organization or something like
that, which can be much easier then code digging.

I can send our CSVs to you (they are small, just about 3204 records in
the A data-set and about 1241 records in the B data-set) and a log as
well.

I have tried to organized oru files as following:
   FEBRL reqirements : Our data
   ==
 'rec_id': RECORD_ID,
 'given_name': 
'surname': 
 'street_num': 
 'address_part_1': 
 'address_part_2': Street + No.
 'suburb': City
   'postcode': Post code
  'state': 
  'date_of_birth': 
 'soc_sec_id': 

Thanks for your answer and suggestions

Petr

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


Re: Why doesn't join() call str() on its arguments?

2005-02-19 Thread Nick Coghlan
news.sydney.pipenetworks.com wrote:
I see your point but I'm not totally convinced  I don't understand 
unicode that well so I'll just be quiet now.
Unicode is horrible, but better than the available alternatives when it comes to 
character sets with more than 128 characters :)

Your point about int and long vs str and unicode is interesting though. 
Does it mean str and unicode will some time in the future be unified 
once all the differences are sorted out ?
Eventually, all Python text strings will be unicode, with a separate type for 
manipulating a sequence of bytes. That's a long way away, though.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Matplotlib, py2exe and pytz

2005-02-19 Thread John Hunter
 scott == scott  [EMAIL PROTECTED] writes:

scott I am trying to convert a python app that uses matplotlib to
scott a standalone executable using py2exe.

scott After running py2exe and executing my app I get the
scott following stack trace:

scott Traceback (most recent call last): File gcToCsv.py, line
scott 5, in ?  File plot_output.pyc, line 1, in ?  File
scott pylab.pyc, line 1, in ?  File matplotlib\pylab.pyc,
scott line 194, in ?  File matplotlib\axes.pyc, line 46, in ?
scott File matplotlib\dates.pyc, line 94, in ?  File
scott pytz\__init__.pyc, line 53, in timezone KeyError: 'UTC'

scott It appears that the instructions on the matplotlib web site
scott and wiki are incomplete and the pytz.zoneinfo package is
scott not being included in the finished dist directory.

In your script that you are trying to freeze, do, 

  import pytz
  import dateutil

as a hint to py2exe that you want these modules.  Does this help?

Does the script you are trying to freeze explicitly use matplotlib
date functionality?

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


Re: Fuzzy matching of postal addresses

2005-02-19 Thread Tim Churches
McBooCzech wrote:
Sorry for my Ferbl typo. 

No offense was caused, I was just joking.
For the local anti-smoking campaign 

As a public health epidemiologist, that's the sort of application of our 
project I like to see! And judging by the reports by Martin Mcgee and 
colleagues at the European Public Health Observatory, such campaigns are 
sorely needed in most of eastern Europe. I am sure Vaclav Havel is 
convinced of the need for anti-smoking campaigns.

I am
trying to link some addresses which contain following linkable
informations (data fields) only:
RECORD_ID, Street + No., City, Post code,
All data are now w/o Unicode characters. Do you think it possible to
try to link it with Febrl w/o deep code modification?
 

Yes.
I did try to link our data but the result is just a plenty of warning
messages but no links. What is your suggestion? Please understand I do
not want to bother you with my questions. I am just asking you your
comments or pointers before I will try to dig in to the code. You
probably know some tricks in data organization or something like
that, which can be much easier then code digging.
I can send our CSVs to you (they are small, just about 3204 records in
the A data-set and about 1241 records in the B data-set) and a log as
well.
I have tried to organized oru files as following:
  FEBRL reqirements : Our data
  ==
'rec_id': RECORD_ID,
'given_name': 
   'surname': 
'street_num': 
'address_part_1': 
'address_part_2': Street + No.
'suburb': City
  'postcode': Post code
 'state': 
 'date_of_birth': 
'soc_sec_id': 
Thanks for your answer and suggestions
 

We would be pleased to assist - but off-list. Please send the exact text 
of the error messages (the log) directly to Peter Christen and myself in 
the first instance. Further discussion of these applictaon-specific 
issues is not appropriate for the general Python list - but you could 
report back to the Python list on your overall experience after we have 
solved the problems with you.

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


Re: exercise: partition a list by equivalence

2005-02-19 Thread bearophileHUGS
John MachinFWIW, here's a brief UAT report:

Here is something else for you.
Note: for more correct comparisons, for the following tests I've
disabled the use of Psyco in Graph (usually enabled, if present).
This looks faster than merge2 for this (quite sparse) random pairs
test:

. import graph # http://www.fantascienza.net/animalia/graph.zip
. def merge4(l):
. g = graph.Graph()
. for n1,n2 in l:
. g.addArc(n1,n2)
. return g.connectedComponents()

Creating a better addArcs produces good results (addArcs method is
present in Graph, but addArcs2 isn't present):

. def merge5(l):
. g = graph.Graph()
. g.addArcs2(l)
. return g.connectedComponents()


If you like to see the actual code, without using Graph, I've made a
very stripped down version of addArcs2 and connectedComponents:

. from collections import deque
. from itertools import chain
.
. def merge6(l):
. # graph creation
. gi = {}
. go = {}
. for n1,n2 in l:
. if n1 not in go:
. go[n1] = {}
. gi[n1] = {}
. if n2 not in go:
. go[n2] = {}
. gi[n2] = {}
. go[n1][n2] = 0
. gi[n2][n1] = 0
. # Connected components:
. result = []
. visited = set()
. for root in go.iterkeys():
. if root not in visited:
. component = [root]
. visited.add(root)
. Q = deque() # A queue
. Q.append(root)
. while Q:
. n1 = Q.popleft()
. for n2 in chain( go[n1].iterkeys(), gi[n1].iterkeys()
):
. if n2 not in visited:
. visited.add(n2)
. Q.append(n2)
. component.append(n2)
. result.append(component)
. return result


At the end of the tests I've added this to be sure the results are
always the same:

r2 = set( frozenset(e) for e in merge2(l) )
r4 = set( frozenset(e) for e in merge4(l) )
r5 = set( frozenset(e) for e in merge5(l) )
r6 = set( frozenset(e) for e in merge6(l) )
assert r2 == r4
assert r2 == r6

For xMax, nPairs = 1000, 5000:
merge2: 15750 function calls in 0.939 CPU seconds
merge4: 11029 function calls in 0.560 CPU seconds
merge5: 6030 function calls in 0.303 CPU seconds
merge6: 6011 function calls in 0.297 CPU seconds

For xMax, nPairs = 2000, 1:
merge2: 31503 function calls in 2.505 CPU seconds
merge6: 12011 function calls in 0.639 CPU seconds

Timings using clock() (much more reliable than the profilers!), for
xMax, nPairs = 2000, 1:
merge2: 1.222
merge6: 0.201

Probably merge6 can be improved, reducing memory used...

Bear hugs,
Bearophile

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


Re: pyFMOD writing a callback function in Python

2005-02-19 Thread Gary Bishop
I haven't tried it on Linux but I believe it should work. FMOD works on Linux 
as does Pyrex.
I don't think there is any win32 specific code. Grab the source and try 
building it. You'll
likely have to fool with the libraries and includes in setup.py.

gb

Marian Aldenh?vel [EMAIL PROTECTED] wrote:
 Hi,

  Check out pySonic, a new FMOD wrapper written with Pyrex. Much more 
  Pythonic.

 I have only found Win32-Downloads. The same is true for pyFMOD. What options
 do I have to make it work on Linux?

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


Re: global var

2005-02-19 Thread Nick Coghlan
Michael Hoffman wrote:
raver2046 wrote:
How to have a global var in python ?

global var will give you a global variable named var.
Whether this advice is correct or not depends greatly on what the OP means by 
'global' :)

Module global, it's right, application global it's wrong. Given the nature of 
the question, I suspect the latter.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Matplotlib, py2exe and pytz

2005-02-19 Thread scott
I unzipped library.zip to see what compiled python files were included
in the zip.
As in the error stacktrace the Pytz.timezone package was not part of
the library.
After manually adding it and rezipping the library I ran into another
missing module, this time it was missing backend_agg

Traceback (most recent call last):
  File gcToCsv.py, line 5, in ?
  File plot_output.pyc, line 1, in ?
  File pylab.pyc, line 1, in ?
  File matplotlib\pylab.pyc, line 195, in ?
  File matplotlib\backends\__init__.pyc, line 20, in ?
ImportError: No module named backend_agg

I added that module and then saw that it was missing pyparsing
Traceback (most recent call last):
  File gcToCsv.py, line 5, in ?
  File plot_output.pyc, line 1, in ?
  File pylab.pyc, line 1, in ?
  File matplotlib\pylab.pyc, line 195, in ?
  File C:\PYTHON23\Lib\site-packages\matplotlib\backends\__init__.py,
line 20,
 in ?
globals(),locals(),[backend_name])
  File
C:\PYTHON23\Lib\site-packages\matplotlib\backends\backend_agg.py,
line
85, in ?
from matplotlib.mathtext import math_parse_s_ft2font
  File C:\PYTHON23\Lib\site-packages\matplotlib\mathtext.py, line
140, in ?
from matplotlib.pyparsing import Literal, Word, OneOrMore,
ZeroOrMore, \
ImportError: No module named pyparsing

After that I stopped adding modules as I figured the problem was more
involved than just missing 1 or 2 modules.

My app just takes a set of data and plots it using the library. It does
not use matplotlib date functionality explicitly, it converts a list of
datatimes to a list of elapsed times (numbers of seconds) and plots
data against these floats.

The setup.py file I used was the one in the matplotlib documentation. I
then added the opt line to try and force the inclusion of that package.


I am relatively new to Python programming coming most recently from a
Java programming background, and was wondering why python does not have
the concept of a python archive much like a jar file in Java.
That would make all of these problems fairly trivial, inclusion of
dependant libraries would just be a matter of having the appropriate
Python ARchive in a directory in the PYTHON_PATH so that it could be
loaded.

Thanks for any help on resolving my py2exe problems.

Scott Snyder

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


Re: [Fwd: Re: [Uuu-devel] languages] -- Why Python

2005-02-19 Thread Nick Coghlan
Mike Meyer wrote:
Arich Chanachai [EMAIL PROTECTED] writes:

Mike Meyer wrote:
Whatever the intentions may be, the *act* is one of dictation. Since
the point of the underlying OS is to increase the interconnections
between applications (assuming I've found the correct web page and
interpreted it correctly), the underlying architecture should be
language-neutral. That allows as many applications as possible to play
in the environment.
*Allowing* other languages is one thing, but that shouldn't preclude having a 
'default' language. On other OS's, the default language is some form of shell 
scripting (i.e. Unix shell scripts, or Windows batch files). It would be good to 
have a real language to fill that role.

You've missed the point. Allowing a wide array of problem solving
choices is a goal, not a means. Instead of concentrating on adding
langauges, you should be provding an infrastructure that makes adding
langauges simple.  The Plan 9 example does this best, as any language
that can do file I/O is supported.
Still, the builtin shell is going to need *some* form of scripting support. And 
if that looks like IPython's shell mode, so much the better.

Anyway, the reason to prefer Python to LISP for something like this, is that 
Python reads much more naturally for most people, whereas LISP requires that you 
write things 'out of order'.

Compare out-of-the-box Python:
  a = 1 + 2 + 3 + 4
And out-of-the-box Lisp:
  (setq a (+ 1 2 3 4))
Which language has the lower barrier for entry? That should be a fairly 
important consideration for a language that is going to sit at the heart of an OS.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


How Do I get Know What Attributes/Functions In A Class?

2005-02-19 Thread steven
Hi,

I'm new to python.  Given a class, how can I get know what
attributes/functins in it without dig into the source?

-
narke

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


Re: [Fwd: Re: [Uuu-devel] languages] -- Why Python

2005-02-19 Thread Nick Coghlan
Paul Rubin wrote:
Nick Coghlan [EMAIL PROTECTED] writes:
Compare out-of-the-box Python:
  a = 1 + 2 + 3 + 4
And out-of-the-box Lisp:
  (setq a (+ 1 2 3 4))
Which language has the lower barrier for entry? That should be a
fairly important consideration for a language that is going to sit at
the heart of an OS.

Huh?  Why does mucking about in the heart of an OS need a low barrier
of entry?
It doesn't. I was looking at it from the point of view of *scripting* the OS - 
which *should* have a low barrier for entry :)

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: lambda closure question

2005-02-19 Thread Ted Lilley
Wow, a lot of great discussion.  Almost a bit too much for me to
grasp...I do see two or more nuggets that really address my issue.

As a side note, I'm familiar with the term currying from a friend who
learned ML and Scheme quite some time ago.  Not sure if that's the true
origin, but it was a sufficiently different context from Python (or at
least I thought) that I didn't want to rely on its meaning.  I was also
sufficiently unsure of it's _exact_ meaning, since we're talking about
two slightly different models, that I didn't want to use the term for
that reason as well.  It's gratifying to know that it was a relevant
concept afterall, the partial function application discussion
notwithstanding.  It's also gratifying to see such a strong community
versed in functional programming styles.  Although I've only started
working with FP in Python, it's been a useful tool for making my
programming simpler.

The first useful nugget is the crystalization method.  I spent some
time thinking about the problem after I posted it and came up with the
same workaround, in fact, the exact same syntax.  It's a bit inelegant,
but it gets the job done for what I want to do.  I won't even attempt
to take a position in the debate about whether Python should work by
default the way it does or the way I want to use it. ;)  Seems we have
well-spoken advocates for both sides.

The other nifty nugget is Kent's suggestion for using old-style Python
default arguments to capture the variable value.  Since it looks
slightly more elegant I'm going to give it a shot.

I have to say, I was happily surprised by the volume and quality of
response to my little issue.  Thanks everyone!

Ted

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


Re: lambda closure question

2005-02-19 Thread Ted Lilley
I replied a few minutes ago thanking everyone for their pointers.  Very
interesting reading.  I don't see my post yet, so I do hope it comes
through.  I'm using a new newsreading service and don't yet have
confidence in it.

In any case, the addition of the default-setting argument in the lambda
works famously and is only a slight modification to my code.  While I
don't think it's particularly intuitive (I would hate to be a
hypothetical programmer trying to puzzle out what my code does), it
gets the job done and is a heck of a lot easier than attaching the list
of attributes manually as I would've done without Python's FP
capabilities.

Thanks again,

Ted

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


Re: [Fwd: Re: [Uuu-devel] languages] -- Why Python

2005-02-19 Thread Donn Cave
Quoth Nick Coghlan [EMAIL PROTECTED]:
[... re Python OS interface vs. language-generic model ]

| *Allowing* other languages is one thing, but that shouldn't preclude having a 
| 'default' language. On other OS's, the default language is some form of shell 
| scripting (i.e. Unix shell scripts, or Windows batch files). It would be good 
to 
| have a real language to fill that role.

I don't know what the Windows version is like, but for all the UNIX
shell's weaknesses, it's very well suited to its role.  The Plan 9
shell (rc) is similar with much improved syntax, and has a distant
relative es that I think is the closest thing I've ever seen to
a 1st class language that works as a shell (though the implementation
was only at the proof of concept level.)  (I'm not forgetting REXX,
it's a fairly respectable effort but not 1st class.)

...
| Still, the builtin shell is going to need *some* form of scripting support. An
| if that looks like IPython's shell mode, so much the better.
|
| Anyway, the reason to prefer Python to LISP for something like this, is that 
| Python reads much more naturally for most people, whereas LISP requires that y
| write things 'out of order'.
|
| Compare out-of-the-box Python:
|a = 1 + 2 + 3 + 4
|
| And out-of-the-box Lisp:
|(setq a (+ 1 2 3 4))
|
| Which language has the lower barrier for entry? That should be a fairly 
| important consideration for a language that is going to sit at the heart of 
an OS.

Well, honestly I think that's stretching it.  Your order issue here
seems to apply only to operators, and they don't really figure that
heavily in the kinds of things we normally do with the OS.  The only
operator I can think of in rc is ^, an odd sort of string multiplication
thing, and I can't think of any in the original Bourne shell.

Meanwhile, the idea that barriers to entry are built out of things like
+ 1 2 3 4 vs. 1 + 2 + 3 + 4 is really quite open to question.

10 years ago when BeOS was a little hotter than it is today, there were
a couple enthusiasts pushing Python as an official language.  A few of
the people following BeOS at that point had come from a strong Amiga
background, and I remember one of them arguing vehemently against Python
because its arcane, complicated syntax was totally unsuited to casual use.
Compared to, say, REXX.

Now, we Python users know very well that's not true, Python's as clear
as could be.  But theoretically, if you wanted to talk about order
issues, for example ... is it really easier to understand when a language
sometimes expresses a function f over x and y this way
f(x, y)
sometimes this way (+ is a function, really)
x f y
and sometimes this way
x.f(y)
?

I don't know, I'm just thinking that while Python's notation might
be just fine for people who've gotten here the way most of us have,
it's not obvious from this that it's just fine 4 everyone.

Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How Do I get Know What Attributes/Functions In A Class?

2005-02-19 Thread Hans Nowak
[EMAIL PROTECTED] wrote:
Hi,
I'm new to python.  Given a class, how can I get know what
attributes/functins in it without dig into the source?
Use the dir function:
 from smtplib import SMTP
 dir(SMTP)
['__doc__', '__init__', '__module__', 'close', 'connect', 'data', 
'debuglevel', 'docmd', 'does_esmtp', 'ehlo', 'ehlo_resp', 'expn', 
'file', 'getreply', 'has_extn', 'helo', 'helo_resp', 'help', 'login', 
'mail', 'noop', 'putcmd', 'quit', 'rcpt', 'rset', 'send', 'sendmail', 
'set_debuglevel', 'starttls', 'verify', 'vrfy']

To get more detailed information than just a list of names, see the 
inspect module.

--
Hans Nowak
http://zephyrfalcon.org/
--
http://mail.python.org/mailman/listinfo/python-list


newbie question - exception processing

2005-02-19 Thread mirandacascade
O/S: Windows XP Service Pack 2
Python version: 2.4

Unable to understand how to build a class to handle an exception.

Contents of sample01.py:
import exceptions
class SampleMain:
try:
def __init__(self):
print 'in SampleMain constructor'

def Allowed(self):
print 'in allowed'

def NotYetAllowed(self):
UCError = UnderConstructionError('not yet ready')
raise UCError

except UnderConstructionError, e:
print e.msg

class Error(exceptions.Exception):
def __init__(self):
print 'in base class constructor'

class UnderConstructionError(Error):
def __init__(self, message):
print 'in UnderConstructionError constructor'
self.msg = message

Copy/paste of interactive window:
PythonWin 2.4 (#60, Nov 30 2004, 09:34:21) [MSC v.1310 32 bit (Intel)]
on win32.
Portions Copyright 1994-2004 Mark Hammond ([EMAIL PROTECTED]) -
see 'Help/About PythonWin' for further copyright information.
 import sample01
 x = sample01.SampleMain()
in SampleMain constructor
 x.NotYetAllowed()
in UnderConstructionError constructor
Traceback (most recent call last):
  File interactive input, line 1, in ?
  File C:\Python24\sample01.py, line 12, in NotYetAllowed
raise UCError
UnderConstructionError: unprintable instance object


My questions are:
1) What is causing the error described in the Traceback?
2) Given that what I want to happen when the NotYetAllowed() method is
called is:
a) an exception to be raised
b) the exception results in a message getting printed; the message
should come from the place where the exception was raised, and it
should be passed to the exception class as a string object; so in this
case the message that should be printed is 'not yet ready'
c) the exception gets handled with the try/except within the
SampleMain class

My question is: what changes must I make to the code to make that
happen?

Thank you.

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


Re: exercise: partition a list by equivalence - merge_JM.py (0/1)

2005-02-19 Thread John Machin
On 19 Feb 2005 17:56:27 -0800, [EMAIL PROTECTED] wrote:

John MachinFWIW, here's a brief UAT report:

Here is something else for you.
Note: for more correct comparisons, for the following tests I've
disabled the use of Psyco in Graph (usually enabled, if present).
This looks faster than merge2 for this (quite sparse) random pairs
test:

[snip]


Timings using clock() (much more reliable than the profilers!), for
xMax, nPairs = 2000, 1:
merge2: 1.222
merge6: 0.201

Probably merge6 can be improved, reducing memory used...

Perhaps I'm missing a posting of yours -- what are merge2 and merge4?
What is this random pairs test? What is xMax (nPairs isn't hard to
guess), and how are you generating your input data?

FWIW, my offering is attached.

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


[ python-Bugs-1144263 ] reload() is broken for C extension objects

2005-02-19 Thread SourceForge.net
Bugs item #1144263, was opened at 2005-02-19 04:20
Message generated for change (Tracker Item Submitted) made by Item Submitter
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1144263group_id=5470

Category: Python Interpreter Core
Group: Python 2.4
Status: Open
Resolution: None
Priority: 5
Submitted By: Matthew G. Knepley (knepley)
Assigned to: Nobody/Anonymous (nobody)
Summary: reload() is broken for C extension objects

Initial Comment:
1) A C extension module (foo.so) is imported

  import foo

2) The library foo.so is rebuilt with changes

3) We reload the module

  foo = reload(foo)

The reload() method calls imp.load_dynamic() which
eventually gets down to _PyImport_GetDynLoadFunc().
This just calls dlopen(), which returns the old filehandle.

This problem can be fixed by augmenting imp with
unload_dynamic(), which could easily be implemented in
a _PyImport_GetDynUnloadFunc(), which would just
consult its handles[] array, and call dlclose() on the
appropriate handle. This will work if Python was the
only program to dlopen() foo.so.

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1144263group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1144533 ] htmllib quote parse error within a script

2005-02-19 Thread SourceForge.net
Bugs item #1144533, was opened at 2005-02-19 13:02
Message generated for change (Tracker Item Submitted) made by Item Submitter
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1144533group_id=5470

Category: Python Library
Group: Python 2.3
Status: Open
Resolution: None
Priority: 5
Submitted By: Allan Hoeltje (ahoeltje)
Assigned to: Nobody/Anonymous (nobody)
Summary: htmllib quote parse error within a script

Initial Comment:
I am using the htmllib to parse web pages for plain text content.  I 
came across a web page that contained a script construct similar 
to the example below.  Note that the script is itself writing a script.  
The htmllib appears to be confused by the use of single and double 
quotes used within the real script and /script tags.

I am using Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 
3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin on a 
PowerBook G4 running OSX 10.3.8.


html
  body
h1 This is a test /h1
br
blockquote
  script language=JavaScript
rnum = Math.round( Math.random() * 10 );
document.write( 'scr' + 'ipt src=http://www.a.org/' + 
rnum + '//scr' + 'ipt' );
  /script
/blockquote
  /body
/html

Here is the Python trace:

Traceback (most recent call last):
  File cleanFeed.py, line 26, in ?
clean = stripHtml.strip( feed )
  File /Users/allan/Desktop/Mood for Today/stripHtml.py, line 
144, in strip
parser.feed(s)
  File /System/Library/Frameworks/Python.framework/Versions/
2.3/lib/python2.3/HTMLParser.py, line 108, in feed
self.goahead(0)
  File /System/Library/Frameworks/Python.framework/Versions/
2.3/lib/python2.3/HTMLParser.py, line 150, in goahead
k = self.parse_endtag(i)
  File /System/Library/Frameworks/Python.framework/Versions/
2.3/lib/python2.3/HTMLParser.py, line 327, in parse_endtag
self.error(bad end tag: %s % `rawdata[i:j]`)
  File /System/Library/Frameworks/Python.framework/Versions/
2.3/lib/python2.3/HTMLParser.py, line 115, in error
raise HTMLParseError(message, self.getpos())
HTMLParser.HTMLParseError: bad end tag: /scr' + 'ipt, at line 
1, column 309




--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1144533group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1144263 ] reload() is broken for C extension objects

2005-02-19 Thread SourceForge.net
Bugs item #1144263, was opened at 2005-02-19 09:20
Message generated for change (Comment added) made by mwh
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1144263group_id=5470

Category: Python Interpreter Core
Group: Python 2.4
Status: Open
Resolution: None
Priority: 5
Submitted By: Matthew G. Knepley (knepley)
Assigned to: Nobody/Anonymous (nobody)
Summary: reload() is broken for C extension objects

Initial Comment:
1) A C extension module (foo.so) is imported

  import foo

2) The library foo.so is rebuilt with changes

3) We reload the module

  foo = reload(foo)

The reload() method calls imp.load_dynamic() which
eventually gets down to _PyImport_GetDynLoadFunc().
This just calls dlopen(), which returns the old filehandle.

This problem can be fixed by augmenting imp with
unload_dynamic(), which could easily be implemented in
a _PyImport_GetDynUnloadFunc(), which would just
consult its handles[] array, and call dlclose() on the
appropriate handle. This will work if Python was the
only program to dlopen() foo.so.

--

Comment By: Michael Hudson (mwh)
Date: 2005-02-19 21:27

Message:
Logged In: YES 
user_id=6656

I don't believe this is quite as easy as you make out.  It might be 
possible to make something that works for platforms that use dlopen 
though...

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1144263group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Bugs-1120452 ] Python 2.4.0 crashes with a segfault, EXAMPLE ATTACHED

2005-02-19 Thread SourceForge.net
Bugs item #1120452, was opened at 2005-02-10 19:04
Message generated for change (Comment added) made by kbk
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1120452group_id=5470

Category: Python Interpreter Core
Group: Python 2.4
Status: Open
Resolution: None
Priority: 5
Submitted By: Viktor Ferenczi (complex)
Assigned to: Nobody/Anonymous (nobody)
Summary: Python 2.4.0 crashes with a segfault, EXAMPLE ATTACHED

Initial Comment:
Running the attached example crashes python 2.4.0 on linux (segfault) and 
Windows. Python is compiled on Debian Linux 3.0r3 (Woody). On Windows XP, I 
used the MSI installer downloaded from python.org

This may be a problem with the regular expression module, but I'm not sure. 
Please assign a new category if it appears as a regexp bug.

This bug causes permanent crashes in my new WEB applications. Old apps not 
using regexp and PyMeld seem to run correctly.

Thanks for 2.4.1.

--

Comment By: Kurt B. Kaiser (kbk)
Date: 2005-02-19 20:56

Message:
Logged In: YES 
user_id=149084

The restart in IDLE will occur if the subprocess is terminated or
segfaults.

--

Comment By: Jim Jewett (jimjjewett)
Date: 2005-02-11 14:55

Message:
Logged In: YES 
user_id=764593

__gettattr__ alone can provoke the crash, if used several 
times, and on sub-melds.

I can print both StreamURL1 and StreamURL2.

If I ask it for p.StreamURL2.src and p.StreamURL1.value, 
it prints whichever one I ask for first, and then crashes on 
the second.  I did get it to print both (not assign, just 
__getattr__) by first getting several other attributes from 
p.StreamURL1, including some that didn't exist, so that 
there was a raise AttributeError in between.  Doing this a 
half dozen times, I provoked a MemoryError.


 p.StreamURL1.value
'mss://stream.url'
 p.StreamURL2.src

Traceback (most recent call last):
  File pyshell#68, line 1, in -toplevel-
p.StreamURL2.src
  File C:\Python24\Lib\site-packages\segfault240\PyMeld.
py, line 475, in __getattr__
start = self._findElementFromID(name)
  File C:\Python24\Lib\site-packages\segfault240\PyMeld.
py, line 425, in _findElementFromID
match = _findIDMatch(nodeID, subset)
  File C:\Python24\Lib\site-packages\segfault240\PyMeld.
py, line 282, in _findIDMatch
match = re.search(thisRE, text)
  File C:\Python24\lib\sre.py, line 134, in search
return _compile(pattern, flags).search(string)
MemoryError
 




--

Comment By: Jim Jewett (jimjjewett)
Date: 2005-02-11 14:36

Message:
Logged In: YES 
user_id=764593

Partially reproduced on Windows XP.  (Using the stock 2.4.
0 msi)  

Just loading it in IDLE and hitting F5 (run), it prints None, 
as though it had succeeded perfectly.

Typing in the commands from index.py by hand, I can get 
it to give me the encountered an error;  Tell Microsoft? 
box, but IDLE only restarts instead of actually crashing.

There seems to a problem between the __getattr__ and 
the __setattr__ in PyMeld.  


 p=Meld(open('player.html','rb').read())
 p.StreamURL1.value
'mss://stream.url'
 p.StreamURL2
PyMeld.Meld instance at 0x00B455F8
 p.StreamURL2.src
'mms://stream.url'

 v=Video()
 v.stream
's'
 p.StreamURL1.value=v.stream
 p.StreamURL1.value

  
RESTART 

 



--

Comment By: Michael Hudson (mwh)
Date: 2005-02-11 09:57

Message:
Logged In: YES 
user_id=6656

What do you do to make it crash?  python index.py?

It doesn't fail for me with CVS HEAD.

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=105470aid=1120452group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com