assigning a custom mapping type to __dict__

2005-03-01 Thread Steven Bethard
I tried to Google for past discussion on this topic, but without much 
luck.  If this has been discussed before, I'd be grateful for a pointer.

Does anyone know why you can't assign a custom mapping type to an 
object's __dict__?

py> class M(object):
... def __getitem__(self, key):
... return 42
... def __setitem__(self, key, value):
... pass
...
py> class C(object):
... pass
...
py> c = C()
py> c.__dict__ = M()
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: __dict__ must be set to a dictionary
I looked at the source in typeobject.c (where this error originates), 
but I'm not fluent enough in CPython yet to be able to tell why a true 
dict type is preferred here over just a mapping type...

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


Re: Google Technology

2005-03-01 Thread Daniel Yoo
[EMAIL PROTECTED] wrote:
: I am just wondering which technologies google is using for gmail and
: Google Groups???

Hello Vijay,

You may want to look at:

http://adaptivepath.com/publications/essays/archives/000385.php

which appears to collect a lot of introductory material about the
client-side Javascript techniques that those applications use.

The LivePage component of Nevow is a Python implementation that does a
lot of the heavy lifing for these kinds of applications:

http://nevow.com/

Best of wishes!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.stat('')[stat.ST_INO] on Windows

2005-03-01 Thread Tim Roberts
Patrick Useldinger <[EMAIL PROTECTED]> wrote:
>
>What does the above yield on Windows? 

0.

>Are inodes supported on Windows NTFS, FAT, FAT32?

No.  Inodes are strictly a Unix filesystem concept.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bsddb for k, v in db.items(): do order the numbers ?

2005-03-01 Thread martijn
oyea, I must convert it to numbers ;)

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


Need direction to kill a virus

2005-03-01 Thread Anthra Norell



Hi all,
 
  Here's an 
operator who instantantly destroys all messages he cannot identify within two 
seconds, saves and inspects all attachments before opening them and 
who thought himself immune from viruses for it. Years of trouble-free 
operation reinforced the perception.
  I recently 
subscribed to this group and had an immediate problem managing the sheer volume 
of messages coming in. The inevitable spam, baits, decoys etc. met their match 
at the door. But soon the junk increased in number and soon reached a 
magnitude where I couldn't help suspecting that I had a problem. The short 
end of it is that my machine seems to generate and spread viruses. It hasn't 
destroyed anything as far as I can tell. It makes the hard drive spin 
continuously over extended time periods, in connection with the Explorer it 
seems. And sometimes it slows down the user interfaces.
  What do I do next, 
one thinks and comes up with a sequence of strategies. But after all of them 
having failed, I am left with the sad impression that these days the production 
of damage motivates as much intelligence or more as the production of benefits. 
Microsoft, Norton and all the other good guys get knocked out by malicious 
hackers. Indeed, the Norton virus scanner doesn't start, not even from the CD. A 
complete reinstallation of the operating system (Windows ME) was ineffective, 
even when started from the CD. I then installed a firewall but cannot start that one either and so the last resort 
seems to be reformatting everything with the nightmarish prospect of 
reconfiguring the machine. The data is backed up, all right. The applications I 
can uninstall, but that doesn't save them.
  All the while I 
think that if I knew the innards ot Windows I'd fix the problem in five minutes. 
So, perhaps one of you guys knows.
  Suggestions greatly 
appreciated.
 
Frederic
 
(Additional info: The virus is a binary file in an 
attachment. A visual inspection of the header reveals a file name: 
'details.txt   
.pif'  (Spaces shove the extension 'pif' out into the peripheral 
vision and the eye's focus is supposed to mistake 'txt' for the 
extension). The other legible words are: Windows Program, KERNEL32.dll, 
LoadLibrary and GetProcAddress.  Follows 30 K of binary 
stuff.)
 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: zlib.decompress cannot, gunzip can

2005-03-01 Thread enrio
Thanks, now the code is

  from cStringIO import StringIO
  from gzip import GzipFile
  ...
  body = GzipFile('','r',0,StringIO(body)).read()

Regards, Enrique

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


Re: assigning a custom mapping type to __dict__

2005-03-01 Thread Daniel Cer
Why not just inherit from dict? That seems to work.
>>> class M(dict):
...   def __getitem__(self,key):
... return 42
...   def __setitem__(self,key,value):
... pass
...
>>> class C(object):
...pass
...
>>> c = C()
>>> c.__dict__ = M()
>>> c.__dict__['x']
42
-Dan
Steven Bethard wrote:
I tried to Google for past discussion on this topic, but without much 
luck.  If this has been discussed before, I'd be grateful for a pointer.

Does anyone know why you can't assign a custom mapping type to an 
object's __dict__?

py> class M(object):
... def __getitem__(self, key):
... return 42
... def __setitem__(self, key, value):
... pass
...
py> class C(object):
... pass
...
py> c = C()
py> c.__dict__ = M()
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: __dict__ must be set to a dictionary
I looked at the source in typeobject.c (where this error originates), 
but I'm not fluent enough in CPython yet to be able to tell why a true 
dict type is preferred here over just a mapping type...

STeVe

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


Re: closing tabs in wxpython

2005-03-01 Thread Steve Holden
Raghul wrote:
I think this need some more explanation.Pls help me to understand this
by giving  an example.
Thanks in advance
Raghul:
I've seen several (hundred ;-) posts of yours in the past couple of 
weeks. It's obvious you are looking for help, but it also seems obvious 
that your level of programming skill is perhaps not yet as advanced as 
your ambitions.

Well, I think you are to be congratulated for being ambitious, and I 
also think it's good for the Python community as a whole to realize from 
time to time that adopting Python as a programming language isn't always 
as easy as we who have already taken that decision might like to think.

It seems, though, that for the moment you might get better-directed help 
from the python-tutor list, where there are people who are (bless them) 
dedicated to helping those who are new not just to python but quite 
often also to programming.

Please forgive me if this advice isn't appropriate, but if you think it 
is then an email to [email protected] might be a lifeline, as I'd hate to 
see your interest in Python spoiled by responses that are above your 
current comprehension level.

If you'd like to know whether the python-tutor list would help you then 
you might like to peruse the archives, which you can see at

  http://mail.python.org/pipermail/tutor/
Last month's archive might be helpful in determining whether the list 
could help you, and you can see that at

  http://mail.python.org/pipermail/tutor/2005-February/date.html
Hope this helps, it certainly isn't meant to offend.
regards
 Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: TKinter

2005-03-01 Thread Steve Holden
anthonyberet wrote:
Steve Holden wrote:
anthonyberet wrote:
So, is it pronounced 'Tee-Kinter', or 'Tee-Kay-Inter'?
I don't want to appear as a dork down the pub.

If anyone down your pub knows enough about Python to understand what 
TKinter is I very much doubt they'll be rude enough to call you a dork 
for displaying your ignorance.

that's-my-kind-of-pub-ly y'rs  - steve

I have never recovered from the time I said 'Lye-Nux' and 'Ess-Kyoo-Ell' 
in the same evening ;|)
in-which-case-you-need-a-new-pub-ly y'rs  - steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: class factory example needed (long)

2005-03-01 Thread Gary Ruben
OK, I've managed to get this to work with Rainer's method, but I 
realised it is not the best way to do it, since the methods are being 
added by the constructor, i.e. they are instance methods. This means 
that every time a foo object is created, a whole lot of code is being 
run. It would be better to do the same thing with class 'static' 
methods, if this is possible, so that the methods are created just once.
Is this possible?
Gary

Rainer Mansfeld wrote:

If OTOH you want your foo class to have sqrt, arccos, etc. methods 
without defining them explicitly, I think you're looking for something 
like:

. import Numeric
.
. class Foo(object):
. def __init__(self, value):
. self.value = float(value)
. for u in ['sqrt', 'cos', 'tan']:
. setattr(self, u, lambda uf=getattr(Numeric, u):
.  uf(self.value + 42.0))
 >>> f = Foo(7)
 >>> f.sqrt()
7.0
HTH
  Rainer
--
http://mail.python.org/mailman/listinfo/python-list


Re: best XSLT processor?

2005-03-01 Thread Steve Holden
[EMAIL PROTECTED] wrote:
This is a good way to kick off a tussle among interested parties, but
hinestly, at this point, most packages work fine.  In my opinion your
rade-off right now is raw speed (e.g. libxslt) versus flexibility (e.g.
4Suite).  All are bug-free enough that you'd have to be doing somethign
*very* exotic to run into trouble.
Just pick one or two and try them.
http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/python-xslt
Uche:
I don't know what news reader you are using, but I wonder if I could ask 
you to retain just a little more context in your posts. If they were 
personal emails I would probably be able to follow the thread, but in a 
newsgroup it's always helpful when I see a comment such as your above if 
I know what the heck you are talking about ;-).

You will notice this post starts by quoting your remarks to make it 
clear exactly where I was looking for context and not finding it. My 
first thought was "*What* is a good way ... ?" - remember, posts don't 
always appear in the same order in everyone's readers/servers.

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


Re: Why do descriptors (and thus properties) only work on attributes.

2005-03-01 Thread Steve Holden
Steven Bethard wrote:
Antoon Pardon wrote:
Can anyone explain why descriptors only work when they are an attribute
to an object or class.  I think a lot of interesting things one can
do with descriptors would be just as interesting if the object stood
on itself instead of being an attribute to an other object.

Not sure what "stood on itself" really means, but if you just want to be 
able to have module-level properties, you can do something like:

Think in non-English (stand outside yourself?) for a second, rememberinf 
Antoon is Belgian (if you knew that):

   "on" => "by"
   "stood on itself" => "stood by itself"
 => "standalone"
regards
 Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: naming convention for scalars, lists, dictionaries ...

2005-03-01 Thread Paul Boddie
[EMAIL PROTECTED] wrote in message news:<[EMAIL PROTECTED]>...
> Since Python does not have declarations, I wonder if people think it is
> good to name function arguments according to the type of data structure
> expected, with names like "xlist" or "xdict".

Your suggestion coincides partly with a mechanism I developed recently
for my libxml2dom package. The normal libxml2dom package puts a
DOM-style wrapper around the existing Python wrapper objects -
something that Python's dynamic features accomplish easily - but this
incurs a major performance cost. Given that a low-level API
(libxml2mod) exists and provides a means to exchange fairly simple
and/or opaque objects with the library, I wondered if I couldn't just
write a code transformer which takes DOM-like code and emits code to
use the low-level API. For example:

  element.childNodes -> libxml2mod.children(element)

The challenge, as you've noted with your mention of declarations, is
to find out whether a particular name refers to an object of a
suitable type for the kind of transformations I have in mind.
(Alternatively, one could just guess that "childNodes" is a DOM-style
attribute and do the transformation, possibly leading to mistaken
transformations taking place.) Whilst type inference might offer a
solution, it is itself a much bigger project than this, so my quick
solution was to permit the annotation of names using prefixes to
indicate which names refer to DOM-style objects. For example:

  # Special magic defined earlier says that x2_ is the chosen prefix.
  x2_element.childNodes -> libxml2mod.children(x2_element)

The result of this is libxml2macro [1], an experimental interface to
libxml2 which manages to retain much of the space/time performance of
that library, albeit without addressing the divisive issues of
transparent memory management. It also offers an insight into the
"optional static typing" parallel universe for Python...

Paul

[1] http://www.boddie.org.uk/python/libxml2dom.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scoping issue with import

2005-03-01 Thread Steve Holden
James Stroud wrote:
Say I have a module, we'll call it "my_imported_mod". It contains a function 
in it that calls another function, "myfun". The "myfun" function is in the 
module "my_main_mod", that imports "my_imported_mod".

The code of "my_main_mod" might look like this:
==
from my_imported_mod import *
def myfun():
  print "stuff"
==
the code of "my_imported_mod" might look like this:
==
def somefun():
  myfun()
==
When trying to execute the function somefun(), I get a
NameError: global name 'myfun' is not defined
How to rectify this with minimal code change? How to let imported modules know 
about the namespace they are getting imported into? I do not want to 
restructure my code right now.

Thanks in advance for help.
James
You have had some good advice about avoiding circular imports.
I just wanted you to consider the coupling of your module. If the called 
function is calling a function inside the module that's calling it, this 
is often a clue that the inner function should be passed as a parameter 
to the first one.

Let me know if this isn't comprehensible and I'll give you an example, 
but to show this being done inside a single module I present the code below:

 >>> def caller(f, arg):
 ...   return f(arg)
 ...
 >>> def call(summat):
 ...   print summat * 3
 ...
 >>> caller(call, 21)
 63
 >>> caller(call, "string")
 stringstringstring
This also demonstrates quite nicely how Python doesn't choose to 
discriminate between integers and strings at compile time, applying the 
correct definition of multiplication when the operation actually has to 
be performed.

Some people hate this, most people who read comp.lang.python regularly 
will be quite happy to explain why it's a Good Thing (tm).

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


Re: yield_all needed in Python

2005-03-01 Thread Steve Holden
Terry Reedy wrote:
"Douglas Alan" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

   We can shorten the code--and make it run in O(N) time--by adding a 
new
   keyword to replace the "for v in ...: yield v" pattern:

Maybe.  Until you define the semantics of yield_all and at least outline an 
implementation, I am not convinced of 'run in o(n) time'.  There was once a 
several-post discussion of a related idea of having yield somehow, 
magically, skip intermediate generators that only yielded value on up, 
without tranformation.  But it was never clear how to do this practically 
without negatively impacting all generators.  Cetainly, if  == , I don't see how anything is 
gained except for a few keystrokes.  If  ==  then the replacement is a semantic change.

La plus ca change, la plus c'est la meme chose (I trust native French 
speakers will excuse the laziness that led to the absence of accent).

This is very reminiscent of discussions several years ago about tail 
recursion and how it would be a great thing to optimise the edge cases. 
Of course we didn't have generators then, so we couldn't complain about 
*their* inefficiencies then.

 def in_order(self):
 if self.left is not None:
 yield_all self.left.in_order():
 yield self.value
 if self.right is not None:
 yield_all self.right.in_order():

If and when I write a text-based double-recursion to iteration transformer, 
a pseudokeyword might be be an idea for indicating that stacked yields are 
identify functions and therefore bypassable.

The key words in the above being "use" and "case", I suspect.
python:-always-something-new-to-bitch-about-ly y'rs  - steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do you control _all_ items added to a list?

2005-03-01 Thread Nick Coghlan
Xif wrote:
Overiding all those methods is too much of an effort. I don't really
need them.
Hmm, it might be nice if there was a UserList.ListMixin that was the counterpart 
to UserDict.DictMixin that let's you provide the full dictionary API with just 
__getitem__, __setitem__, __delitem__ and keys()

With an appropriate ListMixin, providing the first three methods would suffice 
to support the full list API.

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


Re: accessor/mutator functions

2005-03-01 Thread Nick Craig-Wood
Dan Sommers <[EMAIL PROTECTED]> wrote:
>  On 28 Feb 2005 10:30:03 GMT,
>  Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
> 
> > Actually I would say just access the attribute directly for both get
> > and set, until it needs to do something special in which case use
> > property().
> 
> > The reason why people fill their code up with boiler plate get/set
> > methods is to give them the flexibility to change the implementation
> > without having to change any of the users.  In python you just swap
> > from direct attribute access to using property().
> 
>  The reason their code is so inflexible is that they've filled their
>  classes with boiler plate get/set methods.

Amen to that!  As programmers we abhor code duplication, and boiler
plate is just code duplication.  Even if your fancy editor adds it for
you ;-)

>  Why do users of classes need such access anyway?  If my class performs
>  useful functions and returns useful results, no user of my class should
>  care about its attributes.  If I "have to" allow access to my attributes
>  in order that my users be happy, then I did something else wrong when I
>  designed the class and its public interface in the first place.

I would say this is an excellent philosphy for C++ or Java.  When I'm
writing C++ I try to keep the attributes private.  I try not to make
accessor methods at all until absolutely necessary.  I always think
I've failed if I end up writing getBlah and setBlah methods.  In C++
its always in the back of my mind that an inline accessor method will
get optimised into exactly the same code as accessing the attribute
directly anyway.

>  I usually aim for this:  if users of the public interface of my class
>  can figure out that I changed the implementation, then I've exposed too
>  much.  Sure there are exceptions, but that's my basic thought process.

However in python, there is no harm in accessing the attributes
directly.  You can change the implementation whenever you like, and
change the attributes into property()s and the users will never know.

And, as another poster pointed out - you are already accessing the
instance variables just by calling its methods, so you shouldn't feel
too squeamish!

Read only attributes are easy to understand, unlikely to go wrong and
faster than getBlah() accessor methods.

Writable attributes I think are good candidates for methods though.
Looking inside an object is one thing but changing its internal state
is another and should probably be done through a defined interface.

>  Sorry about the rant.

I wouldn't call that a rant, it was quite polite compared to some of
the threads on c.l.p recently ;-)

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: accessor/mutator functions

2005-03-01 Thread Steve Holden
Andrew Dalke wrote:
Me:
What's wrong with the use of attributes in this case and how
would you write your interface?

Dan Sommers:
I think I'd add a change_temperature_to method that accepts the target
temperature and some sort of timing information, depending on how the
rest of the program and/or thread is structured.

[...]
Your "tell_the_device_to_change" is my "self.target" and your
"read_the_temperature_from_the_device" is "self.current_temperature".
In some sense it comes down to style.
Indeed, but it also comes down to control paradigm. I don't *know*, but 
I'll make a guess that Dan, who admits to being "old school", hasn't 
done a lot of work with GUIs, which are inherently event-based.

The difference between your approaches to controlling an external 
process appear to me to be very similar to the differences between the 
traditional "we ask the questions" approach of a batch program (where 
the program logic dictates the sequence of inputs) and the "what just 
happened" approach required by event-driven GUI-based programming.

BTW, had I done this for real I would have two layers, one
which is communications oriented ("send 'get current temperature'
message to device") and my object model which uses the messaging
interface underneath.

I think part of my thinking
comes from my old Pascal days, when it made me cringe to think that
"x:=b;" might actually execute a subroutine rather than just copy some
memory around.

Well, you are clearly more up-to-date on Pascal than me, and I blush to 
recall that I used to *teach* the language (back when "structured 
programming" was supposed to be a novelty).

To give a more recent example for me, which I covered here some
years back, I wrote an OO interface to an "OO-ish" C library
for doing chemistry.  In the data model, atoms have an atomic
symbol, a charge and a list of bonds (and many other things).
Bonds have a bond type and the two atoms at the ends of the bonds
(and many other things).
I liked being able to say:
print atom.symbol, "with charge", atom.charge, "has", \
  len(atom.bonds), "bonds"
for i, bond in enumerate(bonds):
  print "bond", i, "has type", bond.bondtype
To me this is a very natural way of querying the data and
traversing the data structure.
Now underneath the covers it looks like this:
  atom.charge fails so use __getattr__(atom, "charge")
  __getattr__ uses a dispatch table to get the underlying C function
  which is "dt_getcharge"
  return dt_getcharge(self.handle)
where "handle" is the handle used by the C library.
I figured though that this example might be more esoteric
than my PID controller example, though in retrospect it
looks like it might be a better justification.
What this may boil down to is exactly Dan's suggestion that we are all 
comfortable with our own definition of "explicit".

Really, of course, the only things you need to make explicit are the 
ones that readers don't understand :-)

so-you-are-fine-if-there's-only-one-reader-ly y'rs  - steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: accessor/mutator functions

2005-03-01 Thread Steve Holden
Carl Banks wrote:
[EMAIL PROTECTED] wrote:
[...]
My questions are:
a) Are the three things above considered pythonic?

No.  It's not good programming practice in C++, either.
If you have a class that's nothing but a big data structure, you ought
to use it as a data structure.  Writing accessor and mutator methods
for its fields is just doing a lot of work to accomplish nothing.
Unfortunately Java has introduced this as a standard practice, and a lot 
of people who learned their programming by learning Java in the last ten 
years have absolutely no clue what a data structure *is*. (i.e. data, 
with a structure, but no logic required).

If you want to provide access to a certain occasional field, but you're
concerned about keeping the interface backwards-compatible, go ahead
and use them.  But try to observe the following rules of thumb:
1. Don't provide accessor or mutator function to every single member of
every single class you write.  Only provide accessor/mutator functions
if the accessor/mutator methods are a sensible and useful part of the
class's interface.
2. Don't think of these methods as accessors or mutators.  Instead,
think
of them as methods that access or mutate a certain abstract property of
the object that happens to be represented by a single member.
And, keep in mind that, since Python doesn't really have private data,
you don't have to worry about adding these functions to make debugging
easier.

b) What are the tradeoffs of using getattr() and setattr() rather
than creating accessor and mutator functions for each data member?

Don't use getattr and setattr unless you have to construct the name of
the attribute at run time.  That's what they're for.

Well, they are surely helpful in delegation contexts as well, or do I 
misunderstand?

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


Re: assigning a custom mapping type to __dict__

2005-03-01 Thread Nick Coghlan
Daniel Cer wrote:
Why not just inherit from dict? That seems to work.
Because that isn't the question - Steven knows how to make it work, what he's 
curious about is why things are the way they are :)

Anyway, a quick look suggests that it is due to typeobject.c using the concrete 
PyDict_* API calls [1] to manipulate tp_dict, rather than the abstract 
PyMapping_* calls [2]. The reason behind using the concrete API is, presumably, 
a question of speed :)

Cheers,
Nick.
[1] http://www.python.org/dev/doc/devel/api/dictObjects.html
[2] http://www.python.org/dev/doc/devel/api/mapping.html
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: closing tabs in wxpython

2005-03-01 Thread Raghul
Thanx Steve for ur kind advise.And I am in hurry to finish my project.
If this make someone irritating I am sorry.

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


Re: Decimal, __radd__, and custom numeric types...

2005-03-01 Thread Nick Coghlan
Blake T. Garretson wrote:
 If Decimal objects prematurely throw a TypeError before trying the
__rop__, is Decimal broken, or was it designed this way?
I suspect the former, since I can't recall this subject coming up at any point 
during the PEP approval or implementation process. And I was one of the people 
who worked on it before 2.4 was released :)

So I'd suggest:
a) Checking that replacing the relevant "raise TypeError" calls in 
Lib/Decimal.py with "return NotImplemented" gives you friendlier behaviour.

b) Filing a bug report on SF
I'll be bringing the question up on py-dev as well.
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: python-dev Summary for 2005-01-16 through 2005-01-31

2005-03-01 Thread Steve Holden
Michele Simionato wrote [on c.l.py]:
Brett Cannon:
[... python-dev summary ... boilerplate change ...]
+1 for this idea. The summary looks much better now :)
Keep the good work going,
Sorry, but i have to disagree. I hope you won't take this reply 
personally, Michele, since it's directed to all c.l.py readers, as well 
as (particularly) at Python users who [unlike you] are mostly take and 
rather less give. Although this is inherently the nature of open source, 
in certain cases this can be taken too far.

I have a long history of doing things, and an equally long history 
giving up doing them. This stems from a personal belief that organic 
growth (IMHO the healthiest type) will only be engendered by variety.

I was the Chairman of the Sun UK User Group once.
When I was elected I said I would serve for two years, and when I 
resigned after two years many people said to me "Steve, please 
reconsider your decision". I observed, perhaps somewhat cynically, that 
most of the people who said this were motivated by the wish to avoid the 
pain of locating and electing a new chairman.

Guess what ... when I refused to reconsider they found a new chairman, 
who was at least as good as me (I thought he was better), and life 
carried on. If you were to ask a member of the Sun UK User Group now the 
name of their second chairman I'd be very surprised if they had any idea 
who the hell Steve Holden was. (Historical note: the first chairman was 
Chris Brown, and nobody will remember him either).

Now, the reason for this specific rant is this: I can tell a cry for 
help when I see one. Brett has done a magnificent job of providing 
python-dev summaries since Andrew decided he'd had enough, and he is to 
be congratulated for it. I managed to offload another bunch of work on 
him (moderation of various troublesome PyCon mailing lists), but at 
least I was able to recompense him by letting him into PyCon for nothing.

I can say this because I am confident that nobody will even think of 
suggesting that Brett's contribution to the Python community doesn't 
entitle him to a free place at PyCon. I suspect most readers of this 
list would feel the same about Guido (I certainly hope so, because he 
too is a free-loader this year :-). I would actually like a free place 
at PyCon to represent recognition of significant contributions to the 
Python community, but there is a conflict here with another of my goals 
(raising funds for the PSF).

But frankly, I think it's time someone else stood up and said "Brett, 
you've done a magnificent job. Hesitant though I am about replacing you, 
I would like to volunteer for the task, because only when you are free 
from the burden of writing the python-dev summaries will we see what 
else you are capable of". Since I am at best an intermittent reader of 
python-dev I can say this without fear of having to stand up myself.

Oops, I'm rambling. I guess what I'm trying to say boils down to "Ask 
not what the Python community can do for you ...", and anyone who can't 
provide the remainder of the analogy is too young to consider themselves 
a victim of this post, and can claim a free ticket until they are old 
enough ti understand what history is.

I like to think that although I don't make frequent checkins to the code 
base I do *something* to engender the Python community spirit (though I 
don't consider my own interpretation of that spirit to uniquely define 
it), and I'm damned sure Brett has done his share.

It would be great if just a *few* more people who are currently 
consuming the fruits of our labors would stop sitting on the sidelines 
shouting "great job!" and roll their sleeves up.

I hope I'll be able to put these remarks in a corporate context for 
PyCon - which astute readers will have noticed will be my last PyCon as 
chairman. I am happy to say that Andrew Kuchling has finally admitted 
his lust for power and confirmed that he is prepared to act as chairman 
for 2006, and I wish him well. More later

one-more-thing-given-up-ly y'rs  - steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: enter key event in wxpython

2005-03-01 Thread Kartic
Raghul said the following on 2/28/2005 11:59 PM:
hi,
   I am developing a jabber client.What I need is whrn i enter text in
the text area and when I press return key. The following text should be
send.I found the way to send the message, the only thing is I want to
handle the enter key event.how to do this? so that when i press enter
key, The key id or the event to be handled. Help me pls.
Take a look at the KeyEvents demo code under Processes and Events of the 
wxPython Demo application.

In a nutshell, you have to handle the KEY_DOWN and KEY_UP events for the 
window.

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


Re: Why do descriptors (and thus properties) only work on attributes.

2005-03-01 Thread Antoon Pardon
Op 2005-02-28, Dima Dorfman schreef <[EMAIL PROTECTED]>:
> On 2005-02-28, Antoon Pardon <[EMAIL PROTECTED]> wrote:
>> Op 2005-02-28, Diez B. Roggisch schreef <[EMAIL PROTECTED]>:
>>> I still don't see how that is supposed to work for "a lot of interesting
>>> things". Can you provide examples for one of these interesting things?
>>
>> Lazy evaluation where the value of something is calculated the first
>> time it is needed but accessed from some storage if it is needed again.
>
> I do this all the time. It's not very hard and doesn't require any
> extra language support, but I would like for there to be an
> authoritative list of type slots (autopromise_ops).
>
> import operator
>
> def promise(thunk):
> x = []
> def promised():
> if not x:
> x.append(thunk())
> return x[0]
> return promised
>
> autopromise_ops = [x for x in dir(operator) if x.startswith('__')]
> autopromise_ops += ['__getattribute__', '__call__', '__str__', '__repr__']
> autopromise_ops += ['__getattr__', '__setattr__', '__delattr__']
>
> def autopromise(thunk):
> p = promise(thunk)
> d = {}
> for op in autopromise_ops:
> def bindhack(op=op):
> return lambda self, *a, **kw: getattr(p(), op)(*a, **kw)
> d[op] = bindhack()
> return type('autopromise', (), d)()
>
> def test():
>
> lis = []
>
> def thunk():
> lis.append('ran thunk')
> return 'value'
>
> s = autopromise(thunk)
> p = s * 30
> assert p == 'value' * 30
> p = s * 10
> assert p == 'value' * 10
> assert lis == ['ran thunk']  # Just once
>
> print 'autopromise sanity test passed'
>
> An autopromise object is good almost everywhere the real one would be,
> and usually the only way to tell the difference is to call id or type
> on it. The main exception is when the thunk returns a builtin type
> (like a string or int) and you want to pass it to a builtin function
> that expects a particular type (this would also apply to Python
> functions that break duck typing on purpose, but those would just be
> getting the breakage they deserve).

Hmm, I'll have to take your word for it, because for the moment I
don't see what is going on. I'll have to study this some time.

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


Re: ZoDB's capabilities

2005-03-01 Thread Lars
Quote Larry Bates:
> There is a VERY large website that uses Zope/ZODB that takes up to
> 9000 hits per second when it gets busy.

What's the url? I just got curious to see it a big site on Zope in
action.


-
Lars 
"Pythonfan stuck with c sharp"

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


Re: Decimal, __radd__, and custom numeric types...

2005-03-01 Thread Nick Coghlan
Nick Coghlan wrote:
a) Checking that replacing the relevant "raise TypeError" calls in 
Lib/Decimal.py with "return NotImplemented" gives you friendlier behaviour.
It turns out this isn't really practical - there's too much code in the module 
relying on those TypeErrors being raised.

So this may change for Python 2.5 (I think it's a genuine bug), but you're 
probably stuck with it for 2.4 (since changing it is a big enough semantic 
change to break code in the same module, so who knows what it would do to user 
code).

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


MDaemon Warning - virus found: Returned mail: see transcript for details

2005-03-01 Thread Mail Delivery Subsystem

*** WARNING **
Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado 
un fichero anexo(s) infectado(s).  Por favor revise el reporte de abajo.

AttachmentVirus name   Action taken
--
document.zip  Email-Worm.Win32.Mydoom.m Removed


**


The original message was included as attachment

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

Re: Google Technology

2005-03-01 Thread Gurpreet Sachdeva
>>> : I am just wondering which technologies google is using for gmail and
>>> : Google Groups???


Check this:
http://tools.devshed.com/c/a/Search%20Engine%20Tricks/To-the-next-level-with-Google-Groups-2

Regards,
Garry

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


Faster way to do this...

2005-03-01 Thread Harlin Seritt
I've got the following code:

nums = range(0)
for a in range(100):
   nums.append(a)

Is there a better way to have num initialized to a list of 100
consecutive int values?

Thanks,

Harlin

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


Re: python-dev Summary for 2005-01-16 through 2005-01-31

2005-03-01 Thread Gerrit Muller
Brett,
<...snip...>
--
New format
--
I have done a thorough restructuring of the boilerplate and the Summary 
Announcements section for the Summaries.  The purpose of this is to make 
finding information in the boilerplate much easier.  It also keeps 
consistency by sectioning off everything as in the Summary section.

The other reason is for the ``contents`` directive in reST_.  This will 
provide a more thorough table of contents for the web version of the 
summary at the very top of the summaries.  This will allow people to 
jump directly to the section of the Summary they care about the most.  
Obviously this perk only exists in the HTML version.

Lastly, the typical boilerplate for each Summary has now been moved to 
the bottom.  This was at the request of a regular reader who I would 
like to keep happy.  =)  It also seems reasonable since once you have 
read through it once chances are you are not going to read it again so 
might as well move it out of the way.

Then again I could be totally wrong about all of this and manage to 
alienate every person who reads the summaries regularly.  =)

<...snip...>
as always I do appreciate your summaries. This new format, with the 
boilerplate at the end certainly is an improvement. However, I always 
use your news announcement as a trigger to read the version at 
. I used to do this by 
clicking on the "archive" link at the beginning of your message and then 
clicking on the latest summary. For my type of reading I would strongly 
prefer to have the link to the actual version at the top of the message, 
rather than at the end.

I hope you keep summarizing as long as no other volunteer takes over.
thanks, Gerrit
--
Gaudi systems architecting:

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


Re: assigning a custom mapping type to __dict__

2005-03-01 Thread Duncan Booth
Daniel Cer wrote:

> Why not just inherit from dict? That seems to work.
> 
> >>> class M(dict):
> ...   def __getitem__(self,key):
> ... return 42
> ...   def __setitem__(self,key,value):
> ... pass
> ...
> >>> class C(object):
> ...pass
> ...
> >>> c = C()
> >>> c.__dict__ = M()
> >>> c.__dict__['x']
> 42
> 

Didn't test this very much, did you?

>>> c.x

Traceback (most recent call last):
  File "", line 1, in -toplevel-
c.x
AttributeError: 'C' object has no attribute 'x'

Or even:

>>> c = C()
>>> c.__dict__ = M({'x': 1})
>>> c.x
1
>>> c.__dict__['x']
42
>>> 

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


Re: Faster way to do this...

2005-03-01 Thread Will McGugan
Harlin Seritt wrote:
I've got the following code:
nums = range(0)
for a in range(100):
   nums.append(a)
Is there a better way to have num initialized to a list of 100
consecutive int values?
Isn't that equivalent to simply..
nums= range(100)
Will McGugan
--
http://mail.python.org/mailman/listinfo/python-list


Delete first line from file

2005-03-01 Thread Tor Erik Sønvisen
Hi

How can I read the first line of a file and then delete this line, so that 
line 2 is line 1 on next read?

regards 


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


Re: Faster way to do this...

2005-03-01 Thread Steve Holden
Harlin Seritt wrote:
I've got the following code:
nums = range(0)
for a in range(100):
   nums.append(a)
Is there a better way to have num initialized to a list of 100
consecutive int values?
Why not the simplest solution?
  a = range(100)
regards
 Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: accessor/mutator functions

2005-03-01 Thread Dan Sommers
On Tue, 01 Mar 2005 05:37:44 -0500,
Steve Holden <[EMAIL PROTECTED]> wrote:

> Indeed, but it also comes down to control paradigm. I don't *know*,
> but I'll make a guess that Dan, who admits to being "old school",
> hasn't done a lot of work with GUIs, which are inherently event-based.

Not a lot of GUIs, but a lot with (very large, very complex, multi
tasking, multi processor) event-driven embedded stuff, almost all of
which was in C and/or assembly languages.  The C++ stuff I saw made me
want to gouge my eyes out, but a lot of us felt that way at the time,
and we think it came down to the particular (ab)uses of C++ involved.

> Really, of course, the only things you need to make explicit are the
> ones that readers don't understand :-)

+1 QOTW

We used to have holy wars over the appropriate level of comments in
source code.

Regards,
Dan

-- 
Dan Sommers

Îâ à Îâ à c = 1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: accessor/mutator functions

2005-03-01 Thread Dan Sommers
On 01 Mar 2005 10:30:01 GMT,
Nick Craig-Wood <[EMAIL PROTECTED]> wrote:

> However in python, there is no harm in accessing the attributes
> directly.  You can change the implementation whenever you like, and
> change the attributes into property()s and the users will never know.

[ ... ]

> Read only attributes are easy to understand, unlikely to go wrong and
> faster than getBlah() accessor methods.

> Writable attributes I think are good candidates for methods though.
> Looking inside an object is one thing but changing its internal state
> is another and should probably be done through a defined interface.

I wish I'd said it that well in the first place myself.  :-)

Regards,
Dan

-- 
Dan Sommers

Îâ à Îâ à c = 1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Delete first line from file

2005-03-01 Thread Peter Nuttall
On Tue, Mar 01, 2005 at 01:27:27PM +0100, Tor Erik S?nvisen wrote:
> Hi
> 
> How can I read the first line of a file and then delete this line, so that 
> line 2 is line 1 on next read?
> 
> regards 
> 
>

I think you can do something like:

n=false
f=file.open("") #stuff here
g=[]
for line in f.readlines():
if n: g.append(line)
n=true

#write g to file 

if you are on a unix box, then using the standard untils might be a
better idea. 

Pete

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


Re: yield_all needed in Python

2005-03-01 Thread Antoon Pardon
Op 2005-03-01, Steve Holden schreef <[EMAIL PROTECTED]>:
> Terry Reedy wrote:
>> "Douglas Alan" <[EMAIL PROTECTED]> wrote in message 
>> news:[EMAIL PROTECTED]
>> 
>>>We can shorten the code--and make it run in O(N) time--by adding a 
>>>new
>>>keyword to replace the "for v in ...: yield v" pattern:
>> 
>> 
>> Maybe.  Until you define the semantics of yield_all and at least outline an 
>> implementation, I am not convinced of 'run in o(n) time'.  There was once a 
>> several-post discussion of a related idea of having yield somehow, 
>> magically, skip intermediate generators that only yielded value on up, 
>> without tranformation.  But it was never clear how to do this practically 
>> without negatively impacting all generators.  Cetainly, if > iterator> == , I don't see how anything is 
>> gained except for a few keystrokes.  If  == > list(i for i in iterator)> then the replacement is a semantic change.
>> 
> La plus ca change, la plus c'est la meme chose (I trust native French 
> speakers will excuse the laziness that led to the absence of accent).


Small diversion:

You weren't lazy enough because you added words. The idiom AFAIK is:

Plus ça change, plus ça reste la même chose.

You shouldn't add the "la", I think that came from translating
too literally, adding an article to a comparative in french
turns it into a superlative. So instead of writing:

  The more it changes, the more is stays the same

You wrote something like:

  Most it changes, most it is the same thing.

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


Re: ZoDB's capabilities

2005-03-01 Thread Almad
Larry Bates wrote:

> There is a VERY large website that uses Zope/ZODB that takes up to
> 9000 hits per second when it gets busy.  ZODB is very fast and
> holds up well under load.

If it's true, I'm glad. Other side of think is, on what hardware is this
site running :o)

 
> You should probably look at Plone.  It is CMS already built on
> top of Zope.  Might safe you a LOT of work.

I've looked on Plone, I don't want it. My CMS will be somehow very specific,
and I prefer to learn from my programming.


> Larry Bates

-- 
Lukas "Almad" Linhart

[:: http://www.almad.net/ ::]
[:: Humans are too complicated to be described with words. ::]
[:: PGP/GNUPg key: http://www.almad.net/download/pubkey.asc ::]
-- 
http://mail.python.org/mailman/listinfo/python-list


list of all type names

2005-03-01 Thread Klaus Neuner
Hello,

Python has one feature that I really hate: There are certain special
names like 'file' and 'dict' with a predefined meaning. Yet, it is
allowed to redefine these special names as in

dict = [1:'bla']

In order to avoid problems in the future, I tried to get the list of
all those names, but I could not find it. (The Python Reference Manual
only says that there is the type "Dictionary" in Python, but not that
'dict' is a semi-reserved word.) Can you point me to such a list?

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


Re: Delete first line from file

2005-03-01 Thread Pieter Claerhout
what about the following?

f = open( 'file.txt', 'r' )
lines = f.readlines()
f.close()

f = open( 'file.txt'.'w' )
f.write( '\n'.join( lines[1:] ) )
f.close()

cheers,


pieter

On Tue, 1 Mar 2005 12:42:00 +, Peter Nuttall
<[EMAIL PROTECTED]> wrote:
> On Tue, Mar 01, 2005 at 01:27:27PM +0100, Tor Erik S?nvisen wrote:
> > Hi
> >
> > How can I read the first line of a file and then delete this line, so that
> > line 2 is line 1 on next read?
> >
> > regards
> >
> >
> 
> I think you can do something like:
> 
> n=false
> f=file.open("") #stuff here
> g=[]
> for line in f.readlines():
>if n: g.append(line)
>n=true
> 
> #write g to file
> 
> if you are on a unix box, then using the standard untils might be a
> better idea.
> 
> Pete
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 


-- 
pieter claerhout . [EMAIL PROTECTED] . http://www.yellowduck.be/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Decimal, __radd__, and custom numeric types...

2005-03-01 Thread Nick Coghlan
Nick Coghlan wrote:
Nick Coghlan wrote:
a) Checking that replacing the relevant "raise TypeError" calls in 
Lib/Decimal.py with "return NotImplemented" gives you friendlier 
behaviour.

It turns out this isn't really practical - there's too much code in the 
module relying on those TypeErrors being raised.
Then again, maybe it's not so bad:
Py> class C:
...   def __add__(self, other):
... print "OK!"
...   __radd__ = __add__
...
Py> x = decimal.Decimal()
Py> C() + x
OK!
Py> x + C()
Traceback (most recent call last):
  File "", line 1, in ?
  File "C:\Python24\lib\decimal.py", line 906, in __add__
other = _convert_other(other)
  File "C:\Python24\lib\decimal.py", line 2863, in _convert_other
raise TypeError, "You can interact Decimal only with int, long or Decimal da
ta types."
TypeError: You can interact Decimal only with int, long or Decimal data types.
Py> x = friendly_decimal.Decimal()
Py> C() + x
OK!
Py> x + C()
OK!
Cheers,
Nick.
http://boredomandlaziness.skystorm.net/misc/friendly_decimal.py
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: list of all type names

2005-03-01 Thread BJörn Lindqvist
> Python has one feature that I really hate: There are certain special
> names like 'file' and 'dict' with a predefined meaning. Yet, it is
> allowed to redefine these special names as in
>
> dict = [1:'bla']

dir(__builtins__)

Yes, rebinding builtin names accidentally is an annoying and I think
everyone has made that mistake at least once. Maybe PyChecker can
issue a warning?

--
mvh Björn
--
http://mail.python.org/mailman/listinfo/python-list


RE: Delete first line from file

2005-03-01 Thread Alex Stapleton
except them memory usage > file size

at least make sure you do it all on disk :P

# i so tested this first, honest
f = open('file', 'r')
fw = open('file.tmp' ,'w')

lc = 0
for l in f:
if lc != 0:
fw.write(l)
else:
lc = 1
f.close()
fw.close()

import os
os.rename('file.tmp', 'file')


-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] Behalf Of
Pieter Claerhout
Sent: 01 March 2005 12:51
To: [email protected]
Subject: Re: Delete first line from file


what about the following?

f = open( 'file.txt', 'r' )
lines = f.readlines()
f.close()

f = open( 'file.txt'.'w' )
f.write( '\n'.join( lines[1:] ) )
f.close()

cheers,


pieter

On Tue, 1 Mar 2005 12:42:00 +, Peter Nuttall
<[EMAIL PROTECTED]> wrote:
> On Tue, Mar 01, 2005 at 01:27:27PM +0100, Tor Erik S?nvisen wrote:
> > Hi
> >
> > How can I read the first line of a file and then delete this line, so
that
> > line 2 is line 1 on next read?
> >
> > regards
> >
> >
>
> I think you can do something like:
>
> n=false
> f=file.open("") #stuff here
> g=[]
> for line in f.readlines():
>if n: g.append(line)
>n=true
>
> #write g to file
>
> if you are on a unix box, then using the standard untils might be a
> better idea.
>
> Pete
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


--
pieter claerhout . [EMAIL PROTECTED] . http://www.yellowduck.be/
--
http://mail.python.org/mailman/listinfo/python-list

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


RE: Decimal, __radd__, and custom numeric types...

2005-03-01 Thread Batista, Facundo
Title: RE: Decimal, __radd__, and custom numeric types...





[Nick Coghlan]


#- >> a) Checking that replacing the relevant "raise TypeError" 
#- calls in 
#- >> Lib/Decimal.py with "return NotImplemented" gives you friendlier 
#- >> behaviour.
#- > 
#- > 
#- > It turns out this isn't really practical - there's too 
#- much code in the 
#- > module relying on those TypeErrors being raised.
#- 
#- ...
#- 
#- Py> x = friendly_decimal.Decimal()
#- Py> C() + x
#- OK!
#- Py> x + C()
#- OK!


Nick, did you try the test cases with this modification?


.    Facundo


Bitácora De Vuelo: http://www.taniquetil.com.ar/plog
PyAr - Python Argentina: http://pyar.decode.com.ar/



  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ADVERTENCIA.


La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley.

Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo.

Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada.

Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje.

Muchas Gracias.



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

RFC822/M400 Mail Network -- Delivery Report

2005-03-01 Thread Mail Delivery Subsystem
Not delivered to: [EMAIL PROTECTED]
maximum time expired
Original-Envelope-Id: in*vsnl*rfc987;422465891ce8000mimey2k
X400-Content-Identifier: 050301182225+053
Reporting-MTA: x400; /PRMD=rfc987/ADMD=vsnl/C=in
DSN-Gateway: smtp; terminator1.vsnl.net.in

Final-Recipient: rfc822;
	S=pnv/G=venugopal/PRMD=gems/ADMD=vsnl/[email protected]
Action: failed
Diagnostic-Code: x400; 0 5
Status: 5.1.1
Last-Attempted-Date: 1  Mar 2005 18:22 +0530
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Faster way to do this...

2005-03-01 Thread Aaron Bingham
Harlin Seritt wrote:
I've got the following code:
nums = range(0)
for a in range(100):
   nums.append(a)
Is there a better way to have num initialized to a list of 100
consecutive int values?
You mean like this?
nums = range(100)
;-)
--

Aaron Bingham
Software Engineer
Cenix BioScience GmbH

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


Re: Decimal, __radd__, and custom numeric types...

2005-03-01 Thread Nick Coghlan
Batista, Facundo wrote:
[Nick Coghlan]
#- >> a) Checking that replacing the relevant "raise TypeError"
#- calls in
#- >> Lib/Decimal.py with "return NotImplemented" gives you friendlier
#- >> behaviour.
#- >
#- >
#- > It turns out this isn't really practical - there's too
#- much code in the
#- > module relying on those TypeErrors being raised.
#-
#- ...
#-
#- Py> x = friendly_decimal.Decimal()
#- Py> C() + x
#- OK!
#- Py> x + C()
#- OK!
Nick, did you try the test cases with this modification?
Yep - and I was pleasantly surprised when they all passed with -udecimal, 
too.
My implementation is a bit hackish though - if this gets fixed for real, it 
should be possible to devise something that doesn't trample all over performance 
like I'm sure the version I linked to does.

Anyway, I've put the question to python-dev if you'd like to chime in over 
there. It's still your module after all :)

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


Re: java crashes in python thread

2005-03-01 Thread Peter Hansen
Easeway wrote:
I use os.system invoking java VM, when running in python thread, 
the java application crashes.  
Can you define "crash" more precisely?  Isn't there any
kind of error message/traceback that would reveal more
information about the problem?
Also, how quickly do you get this crash?  Instantly,
shortly after starting, a long time after starting,
at completion of the Java processes (maybe check to
see whether the entire javac has executed, or some
other sign of completion), or ?
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


windows bat file question

2005-03-01 Thread Tom Willis
I'm trying to get pylint running on windows and the bat file for it
seems a little screwy. I'm hoping someone may have figured this out
already.

rem = """-*-Python-*- script
@echo off
rem  DOS section 
rem You could set PYTHONPATH or TK environment variables here
python %*
goto exit
 
"""
#  Python section 
import sys
from logilab.pylint import lint
lint.Run(sys.argv[1:])
 

DosExitLabel = """
:exit
rem """

All I get is the python prompt, the lines starting at import sys don't
run.  If I throw the lines in a python script, I run into path issues.

The overall effect I'm trying to achieve is

c:\Projects\myproject\pylint mymodule.py



Any ideas?

-- 
Thomas G. Willis
http://paperbackmusic.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Module RE, Have a couple questions

2005-03-01 Thread [EMAIL PROTECTED]
(1) How do I perform a search for "word" and have it return every line
that this instance is found?

(2) How do I perform a search for "word" and "wordtwo" at the same time
to return every line these instances are found so that the order in
which these lines are in are left intact.

If there's another standard module more suited for this let me know,
and no I dont want to use sed :)

Thanks

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


Re: [Tutor] printing out a box of O's

2005-03-01 Thread Rainer Mansfeld
Kevin wrote:
I just started getting in to python and for taking a look at the for
loop. I want to print out a box
of O's 10o chars long by 10 lines long this is what I came up with. Is
there a better way to do
this:
j = 'O'
for i in j*10:
print i * 100
Thanks
Kevin
Hi Kevin,
I don't know, if this is better, but at least it's shorter:
>>> print ('O' * 100 + '\n') * 10
  Rainer
--
http://mail.python.org/mailman/listinfo/python-list


Re: canvassing for assistance

2005-03-01 Thread [EMAIL PROTECTED]
Sean, nice work on canvasser!  One question: what is the purpose of
'scale'?  I notice that if you have already drawn a line on the canvas,
then 'scale' can be used to draw a straight-line element extending from
the end of the previous freehand line, but if you start with a blank
screen, 'scale' has no effect.

BTW if you want to extend your app further, take a look at paint.py in
the Vaults of Parnassus:
http://py.vaults.ca/apyllo.py?i=173784088

cheers,
S

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


Tkinter and Text() widget interactivity ?

2005-03-01 Thread Tonino
Hi,

I have a small Tkinter app that gets data from a socket connection to a
"server".  The app has a Text() widget to display the info that it gets
from the socket connection.  I have the ability to stop the text at any
point.

What I want to be able todo is select a line from the Text() window and
double click or whatever on it to open a new window with that selected
text as a paramater to the new window.

The app is a network sniffer and I want to be able to select a line
from the Text() window and run a decode on the data from the sniffer.

any help and pointers would help.  I have no idea of what to search for
;)

Thanks

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


[Twisted] potential bug in the reactor's handling events loop

2005-03-01 Thread Andy Leszczynski
Python 2.3, one of the latest Twisted version:
I noted that under Linux there is not way to Control-C the reactor loop. 
After digging a little I found that following change helpes:

[EMAIL PROTECTED] internet]# diff base.py{,.ori}
>
302d301
<   print "1",sysEvtTriggers
305d303
<   print "2",`self._eventTriggers`
307,308c305
< for callable, args, kw in sysEvtTriggers[1]:
<   print "3"
---
>
> for callable, args, kw in sysEvtTriggers[0]:
317d313
<   print "4"
320d315
<   print "5",`eventType`
Of course it is quick work around, not a permanent fix, but it really helps.
Please advice, Andy
--
http://mail.python.org/mailman/listinfo/python-list


Re: windows bat file question

2005-03-01 Thread Peter Hansen
Tom Willis wrote:
I'm trying to get pylint running on windows and the bat file for it
seems a little screwy. I'm hoping someone may have figured this out
already.
...
All I get is the python prompt, the lines starting at import sys don't
run.  If I throw the lines in a python script, I run into path issues.
What exact command are you typing to try to run it?  Where is
the script relative to the current directory?(Best is to
cut and paste a copy of the actual command line and result
that you have in your console.)
On the topic of the "path issues" in the other case, what do you
mean by path issues?  DOS path issues?  sys.path issues?  Something
else?  What issues exactly...
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem installing wxPython 2.5.3, wxWidgets installed ok

2005-03-01 Thread timothy . williams
Luc wrote:
> [EMAIL PROTECTED] a écrit:
>
> > I'm trying to install wxPython 2.5.3.1 using Python 2.3.2 on a
Fedora 2
> > machine.
> >
> > I have python in a non-standard place, but I'm using --prefix with
the
> > configure script to point to where I have everything. The make
install
> > in $WXDIR seemed to go fine. I have the libxw* libraries in my lib/
> > directory
> >
(snip)
> pay attention: some of your current applications will not work with
that
> version. In my case, all the apps I have wrotten before and with
previous
> 2.4 as well with the boa-constructor IDE

So are you saying that 2.5.3.1 is not ready for prime time? How does
your reply address my 'python setup.py install' problem?

I don't have any wx applications to speak of yet. Just some of the
tutorial examples.

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


Re: list of all type names

2005-03-01 Thread Peter Maas
Klaus Neuner schrieb:
Python has one feature that I really hate: There are certain special
names like 'file' and 'dict' with a predefined meaning. Yet, it is
allowed to redefine these special names as in
This is not a specific Python feature: If you include a header file
in C that redefines fopen(), wou will probably also run into problems.
dict = [1:'bla']
I would avoid the use of generic names for variables but rather use
dict1 or aDict etc. If you want to avoid a name collision without
the use of naming conventions you could rename __builtins__:
bi = __builtins__
del __builtins__
Then you can define what you like but you will have to reference dict,
list etc. as bi.dict, bi.list, ...
For a fast check simply type e.g.
dict
in the interactive Interpreter. If you get a NameError it is not
built-in. :)
--
---
Peter Maas,  M+R Infosysteme,  D-52070 Aachen,  Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
---
--
http://mail.python.org/mailman/listinfo/python-list


Re: Faster way to do this...

2005-03-01 Thread Roy Smith
Harlin Seritt <[EMAIL PROTECTED]> wrote:
>I've got the following code:
>
>nums = range(0)
>for a in range(100):
>   nums.append(a)
>
>Is there a better way to have num initialized to a list of 100
>consecutive int values?

Step one would be to change the first line to

nums = []

which is simpler and results in the same thing.  Or, you could write
the whole thing as a one-liner using a list comprehension

nums = [a for a in range(100)]

and then you can take it one step further and just write

nums = range(100)

which I think is about as simple as you can get.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Validating A User/Password Pair + Getting Groups On Unix

2005-03-01 Thread Skip Montanaro
>> 1) Validate that the password is correct for that user *without
>>actually logging in*.
>> 
Kanenas> The 'pwd' module probably won't be able (and won't try) to read
Kanenas> the shadow password file, so 'pwd' won't be of use.  

Note that an spwd module was recently added to Python's CVS repository.  I
imagine it will be in 2.5.

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


Re: windows bat file question

2005-03-01 Thread Tom Willis
On Tue, 01 Mar 2005 10:12:29 -0500, Peter Hansen <[EMAIL PROTECTED]> wrote:
> Tom Willis wrote:
> > I'm trying to get pylint running on windows and the bat file for it
> > seems a little screwy. I'm hoping someone may have figured this out
> > already.
> > ...
> > All I get is the python prompt, the lines starting at import sys don't
> > run.  If I throw the lines in a python script, I run into path issues.
> 
> What exact command are you typing to try to run it?  Where is
> the script relative to the current directory?(Best is to
> cut and paste a copy of the actual command line and result
> that you have in your console.)
> 
> On the topic of the "path issues" in the other case, what do you
> mean by path issues?  DOS path issues?  sys.path issues?  Something
> else?  What issues exactly...
> 
> -Peter
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

I figured it out. I just took the embedded python code that was in the
batch file distributed with it and put it in it's own module.

Really my question was how would this ever work? It seems to me to be
a little screwy, but it would be handy to know if this was some sort
of convention that I could take advantage of if I ever write something
substantial that would need to run on windoze.


REM---bat file---
rem = """-*-Python-*- script
@echo off
rem  DOS section 
rem You could set PYTHONPATH or TK environment variables here
python %*
goto exit

"""
#  Python section 
print "hello from python"

DosExitLabel = """
:exit
rem """
REM---end of bat file---

I'm wondering if this took advantage of some flaw in batch file
processing that can no longer be used because of some security hole
that got plugged or something.




-- 
Thomas G. Willis
http://paperbackmusic.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Module RE, Have a couple questions

2005-03-01 Thread Marc Huffnagle
Dasacc
There is a better (faster/easier) way to do it than using the re module, 
the find method of the string class.

[EMAIL PROTECTED] wrote:
(1) How do I perform a search for "word" and have it return every line
that this instance is found?
[line for line in document if line.find('a') != -1]
(2) How do I perform a search for "word" and "wordtwo" at the same time
to return every line these instances are found so that the order in
which these lines are in are left intact.
[line for line in document if (line.find('word') != -1 \
and line.find('wordtwo'))]
If there's another standard module more suited for this let me know,
and no I dont want to use sed :)
Thanks
--
http://mail.python.org/mailman/listinfo/python-list


Re: Module RE, Have a couple questions

2005-03-01 Thread Marc Huffnagle
Oops, made a mistake.
Marc Huffnagle wrote:
Dasacc
There is a better (faster/easier) way to do it than using the re module, 
the find method of the string class.

[EMAIL PROTECTED] wrote:
(1) How do I perform a search for "word" and have it return every line
that this instance is found?

[line for line in document if line.find('a') != -1]
(2) How do I perform a search for "word" and "wordtwo" at the same time
to return every line these instances are found so that the order in
which these lines are in are left intact.

[line for line in document if (line.find('word') != -1 \
and line.find('wordtwo'))]
This should have been:
[line for line in document if (line.find('word') != -1 \
and line.find('wordtwo') != -1)]

If there's another standard module more suited for this let me know,
and no I dont want to use sed :)
Thanks
--
http://mail.python.org/mailman/listinfo/python-list


Re: list of all type names

2005-03-01 Thread Calvin Spealman
Of course, remember that there are benefits to this, as well. Redefining the
built-ins can be useful in some interesting cases.

Klaus Neuner wrote:

> Hello,
> 
> Python has one feature that I really hate: There are certain special
> names like 'file' and 'dict' with a predefined meaning. Yet, it is
> allowed to redefine these special names as in
> 
> dict = [1:'bla']
> 
> In order to avoid problems in the future, I tried to get the list of
> all those names, but I could not find it. (The Python Reference Manual
> only says that there is the type "Dictionary" in Python, but not that
> 'dict' is a semi-reserved word.) Can you point me to such a list?
> 
> Klaus

-- 
 

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


Initializing subclasses of tuple

2005-03-01 Thread Dave Opstad
I'm hoping someone can point out where I'm going wrong here. Here's a 
snippet of a Python interactive session (2.3, if it makes a difference):

--
>>> class X(list):
...   def __init__(self, n):
... v = range(n)
... list.__init__(self, v)
... 
>>> x = X(10)
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> class Y(tuple):
...   def __init__(self, n):
... v = tuple(range(n))
... tuple.__init__(self, v)
... 
>>> y = Y(10)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: iteration over non-sequence
--

How do I initialize instances of a class derived from tuple, if it's not 
in the __init__ method?

Thanks for any help!
Dave Opstad
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyAC 0.1.0

2005-03-01 Thread gry

Premshree Pillai wrote:
> PyAC 0.1.0 (http://sourceforge.net/projects/pyac/)
>
> * ignores non-image files
> * optional arg is_ppt for ordering presentation images (eg.,
> Powerpoint files exported as images)
> * misc fixes
>
> Package here:
http://sourceforge.net/project/showfiles.php?group_id=106998&package_id=115396&release_id=309010

A few suggestions:

   Always include in the announcement a brief description of what the
software
does -- most people will not bother to track down the link to decide if
the
package is of interest to them.

   Also mention any dependencies not included in the standard
installation,
e.g. "requires PIL".

   You should probably look at the distutils
(http://docs.python.org/dist/dist.html) module for a clean platform-
independant way for users to install your module.  Editing paths in the
source code is not too cool ;-).

And thanks for contributing to the python community!  Have fun!

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


ANN: xsdbXML python release with C#/.NET port

2005-03-01 Thread aaronwmail-usenet
ANN: xsdbXML release with C#/.NET port

Part I: Announcement

There is a new release of xsdbXML which provides
bugfixes to the Python implementation and also
provides a completely separate implementation in C#/.NET.

The xsdb framework provides a flexible and well defined
infrastructure to allow tabular data to be published,
retrieved, and combined over the Internet.

Read more and download at
   http://xsdb.sourceforge.net

Part II: Discussion
===
The C# implementation is primarily a transliteration
of the Python implementation.  I hope to also do a java
transliteration of the C# code.  Some brief observations:

- Development:
Using python for the first implementation was the
right way to go because it made it easier to backtrack
and refactor the implementation.  If I had tried this
in C# backtracking would have been much more painful.
Testing Python code, especially during development, is also
much easier in part because you can write
{"a": [1,2,3], "b": MyClass("argument")}
in a few keystrokes whereas a C# analogue runs to many
lines.
Interestingly, however, the C# port exposed several
nasty bugs in untested code paths of the python
implementation (incorrect calling sequences) because of C#
static typing, even before the C# code was running or
even compiling.
For the most part the transliteration was
straightforward, except where the python implementation
leans on the python expression parser (the parser had
to be "hand rolled" in C#).

- Libraries:

The python http services are more "bare bones" than the
.NET libraries and this is a *GOOD* *THING* (tm).  The
.NET libraries seem to do all kinds of nice things under
the surface where I can't influence their behavior (even
in principal because of the type system information hiding).
The python implementation pretty much allows me to
modify any part of the implementation, and the default does
as little as possible.  My reservations about the C# http
services didn't actually cause problems in this case, but
it made me nervous.

On the other hand it's nice in C# to not have to guess about
which XML library to use.  As any python programmer can
attest it is not fun trying to decide which of several
implementations is the best and will stay alive, etcetera.
I just arbitrarily chose the one I knew already, but I
really should switch to something else, dunno what.
In C# there is only one choice.

- Environment

What can I say. VS/.NET is really nice and there is
nothing close in Python AFAIK.

- Conclusion

Don't have any.  I'm just making comments :).

  Thanks for your attention -- Aaron Watters

===
% if I had a ( for every $ bush spent how many ('s would I have?
too many ('s

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


Re: Faster way to do this...

2005-03-01 Thread Warren Postma
Will McGugan wrote:
Isn't that equivalent to simply..
nums= range(100)
I remember the day I first realized that 900 lines of some C++ program I 
was working on could be expressed in three lines of python.  Ahh.
Rebirth.  Then there was the phase of the python-newbie so enamored of 
map and lambda.  ... Wait, actually, I'm not out of that yet. :-)

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


Re: windows bat file question

2005-03-01 Thread Steve Holden
Tom Willis wrote:
On Tue, 01 Mar 2005 10:12:29 -0500, Peter Hansen <[EMAIL PROTECTED]> wrote:
Tom Willis wrote:
I'm trying to get pylint running on windows and the bat file for it
seems a little screwy. I'm hoping someone may have figured this out
already.
...
All I get is the python prompt, the lines starting at import sys don't
run.  If I throw the lines in a python script, I run into path issues.
What exact command are you typing to try to run it?  Where is
the script relative to the current directory?(Best is to
cut and paste a copy of the actual command line and result
that you have in your console.)
On the topic of the "path issues" in the other case, what do you
mean by path issues?  DOS path issues?  sys.path issues?  Something
else?  What issues exactly...
-Peter
--
http://mail.python.org/mailman/listinfo/python-list

I figured it out. I just took the embedded python code that was in the
batch file distributed with it and put it in it's own module.
Really my question was how would this ever work? It seems to me to be
a little screwy, but it would be handy to know if this was some sort
of convention that I could take advantage of if I ever write something
substantial that would need to run on windoze.
REM---bat file---
rem = """-*-Python-*- script
@echo off
rem  DOS section 
rem You could set PYTHONPATH or TK environment variables here
python %*
goto exit
"""
#  Python section 
print "hello from python"
DosExitLabel = """
:exit
rem """
REM---end of bat file---
I'm wondering if this took advantage of some flaw in batch file
processing that can no longer be used because of some security hole
that got plugged or something.


It was clearly originally intended to be run as "name" and then pipe the 
batch file into the Python interpreter, but as to how the hell it was 
actually supposed to work, your guess is as good as mine.

regards
 Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.pycon.org/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Initializing subclasses of tuple

2005-03-01 Thread Steve Holden
Dave Opstad wrote:
I'm hoping someone can point out where I'm going wrong here. Here's a 
snippet of a Python interactive session (2.3, if it makes a difference):

--
class X(list):
...   def __init__(self, n):
... v = range(n)
... list.__init__(self, v)
... 

x = X(10)
x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
class Y(tuple):
...   def __init__(self, n):
... v = tuple(range(n))
... tuple.__init__(self, v)
... 

y = Y(10)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: iteration over non-sequence
--
How do I initialize instances of a class derived from tuple, if it's not 
in the __init__ method?

In the __new__ method! This must return the actual created object, 
whereas __init__ initializes the already-created object.

This applies to subclassing all the built-in types.
regards
 Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.pycon.org/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Initializing subclasses of tuple

2005-03-01 Thread Just
In article <[EMAIL PROTECTED]>,
 Dave Opstad <[EMAIL PROTECTED]> wrote:

> I'm hoping someone can point out where I'm going wrong here. Here's a 
> snippet of a Python interactive session (2.3, if it makes a difference):
> 
> --
> >>> class X(list):
> ...   def __init__(self, n):
> ... v = range(n)
> ... list.__init__(self, v)
> ... 
> >>> x = X(10)
> >>> x
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
> >>> class Y(tuple):
> ...   def __init__(self, n):
> ... v = tuple(range(n))
> ... tuple.__init__(self, v)
> ... 
> >>> y = Y(10)
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: iteration over non-sequence
> --
> 
> How do I initialize instances of a class derived from tuple, if it's not 
> in the __init__ method?

Hi Dave,

You're going to have to override __new__. See eg.


http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread
/4a53d2c69209ba76/9b21a8326d0ef002

http://mail.python.org/pipermail/tutor/2004-January/027779.html

Good luck,

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


Re: cannot open file in write mode, no such file or directory

2005-03-01 Thread David Bolen
[EMAIL PROTECTED] writes:

> I'm having a problem where when trying to open a file in write mode, I
> get an IOError stating no such file or directory.  I'm calling an
> external program which takes an input file and produces an output file
> repeatedly, simulating the input file separately for each replicate.
> The error occurs when trying to open the input file to write out the
> new data.  The problem is difficult to reproduce since it only shows up
> once every few thousand replicates.  I've tried using both os.system
> and os.popen to invoke the external program.  Originally I was running
> this on cygwin, but also tried under windows.

You might be hitting a race condition where the OS is still
considering the file to be in use when you get around to rewriting it,
even if the using application has just exited.  I've run into similar
problems when trying to rename temporary files under NT based systems.

The problem can be obscured because some of the Win32-specific IO
errors can turn into more generic IOError exceptions at the Python
level due to incomplete mappings available for all Win32 errors.  In
particular, a lot of Win32-layer failures turn into EINVAL errno's at
the C RTL level, which Python in turn translates to ENOENT (which is
the file not found).  So the IOError exception at the Python level can
be misleading.

Since it sounds like you can reproduce the problem relatively easily
(just run your application several thousand times), a quick check for
this condition would be to trap the IOError, delay a few seconds (say
5-10 to be absolutely sure, although in the cases I've run into 2-3 is
generally more than enough), and retry the operation.  If that
succeeds, then this might be the issue you're hitting.

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


Re: Initializing subclasses of tuple

2005-03-01 Thread gry
To inherit from an immutable class, like string or tuple, you need to
use the __new__ member, not __init__.  See, e.g.:

http://www.python.org/2.2.3/descrintro.html#__new__

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


memory leaks with ctypes LoadLibrary ?

2005-03-01 Thread chris
What is the proper way to use ctypes to access an exported Function in
a dll file on windows?  I must be missing something because I get
memory leaks when I  use it:

import ctypes
import gc

gc.enable()
gc.set_debug(gc.DEBUG_LEAK)
lib = ctypes.windll.LoadLibrary("H:\lib\mylib.dll")
fn = lib.myfn
fn("test")
del fn
del lib
gc.collect()
gc: uncollectable 
gc: uncollectable 
gc: uncollectable <_StdcallFuncPtr 015DAE48>
gc: uncollectable 
4

What am I doing wrong?

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


smtplib Segfaults Python under Debian

2005-03-01 Thread Alex Stapleton
localhost:~alex#python
Python 2.3.3 (#2, Feb 24 2004, 09:29:20)
[GCC 3.3.3 (Debian)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import smtplib
Segmentation fault (core dumped)

This happens under python 2.2 and 2.3 and 2.4

argh!

everything else seems to be ok, any ideas anyone? I believe this to be the
debian testing version.

Debian is a PITA at times :/

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


Re: assigning a custom mapping type to __dict__

2005-03-01 Thread Daniel Cer
> > Why not just inherit from dict? That seems to work.
>
> Because that isn't the question - Steven knows how to make it work, what he's
> curious about is why things are the way they are :)

Sorry, didn't mean to be a pest :)

I guess I assumed Steve already knew that he could inherit from dict.
That being said, I was wondering why pragmatically this wouldn't be the
right thing to do (in order to do what he seemed to want to do).

 braces self for the true but not always too informative response of
'in principle, it's best to use the most abstract interface possible'

-Dan


>
> Anyway, a quick look suggests that it is due to typeobject.c using the 
> concrete
> PyDict_* API calls [1] to manipulate tp_dict, rather than the abstract
> PyMapping_* calls [2]. The reason behind using the concrete API is, 
> presumably,
> a question of speed :)
>
> Cheers,
> Nick.
>
> [1] http://www.python.org/dev/doc/devel/api/dictObjects.html
> [2] http://www.python.org/dev/doc/devel/api/mapping.html
> --
> Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
> ---
>  http://boredomandlaziness.skystorm.net
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: smtplib Segfaults Python under Debian

2005-03-01 Thread Skip Montanaro

Alex> localhost:~alex#python
Alex> Python 2.3.3 (#2, Feb 24 2004, 09:29:20)
Alex> [GCC 3.3.3 (Debian)] on linux2
Alex> Type "help", "copyright", "credits" or "license" for more information.
 import smtplib
Alex> Segmentation fault (core dumped)

Can you file a bug report on SF so this doesn't get lost?  Can you run
Python under gdb and get a C stack trace?

Alex> everything else seems to be ok, any ideas anyone? I believe this
Alex> to be the debian testing version.

Alex> Debian is a PITA at times :/

If you suspect it's a Debian issue I suggest you file a bug report there as
well.

Skip

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


(no subject)

2005-03-01 Thread python-list-bounces+archive=mail-archive . com
#! rnews 1106
Newsgroups: comp.lang.python
Path: 
news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!wns13feed!worldnet.att.net!12.120.4.37!attcg2!ip.att.net!xyzzy!nntp
From: Jeff Sandys <[EMAIL PROTECTED]>
Subject: Re: Delete first line from file
X-Nntp-Posting-Host: e515855.nw.nos.boeing.com
Content-Type: text/plain; charset=iso-8859-1
Message-ID: <[EMAIL PROTECTED]>
Sender: [EMAIL PROTECTED] (Boeing NNTP News Access)
Content-Transfer-Encoding: 8bit
Organization: juno
X-Accept-Language: en
References: <[EMAIL PROTECTED]>
Mime-Version: 1.0
Date: Tue, 1 Mar 2005 16:41:02 GMT
X-Mailer: Mozilla 4.79 [en]C-CCK-MCD Boeing Kit  (Windows NT 5.0; U)
Xref: news.xs4all.nl comp.lang.python:365187
Lines: 23

You describe the standard behavior, unless you close the file, 
is that what you want to do; open file, read line 1, close file,
then open file, read line 2, close file?  The other suggestions 
here destory content, do you want that?

>>> f = open("D:/Pydev/test.txt")
>>> f.readline()
'line one\n'
>>> f.readline()
'line two\n'
>>> f.readline()
'line three\n'


"Tor Erik Sønvisen" wrote:
> 
> Hi
> 
> How can I read the first line of a file and then delete this line, so that
> line 2 is line 1 on next read?
> 
> regards
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pyallegro status (is it dead?). What about pygame.

2005-03-01 Thread PrzemysÅaw RÃÅycki
Thanks for your answers.
I wanted to programme in pyallegro, because it seems that allegro has 
much more followers than SDL (on which pygame is based). I had also the 
feeling that the former (allegro) is more convenient in high level game 
programming. But due to the state of pyallegro maturity I'll dedicate my 
time to pygame.

PrzemysÅaw RÃÅycki
--
http://mail.python.org/mailman/listinfo/python-list


Re: any Python equivalent of Math::Polynomial::Solve?

2005-03-01 Thread Cousin Stanley
Alex 
  Thanks for posting your generalized numarray
  eigenvalue solution 
  It's been almost 30 years since I've looked at
  any characteristic equation, eigenvalue, eignevector
  type of processing and at this point I don't recall
  many of the particulars 
  Not being sure about the nature of the monic( p ) function,
  I implemented it as an element-wise division of each
  of the coefficients 
  Is this anywhere near the correct interpretation
  for monic( p ) ?
  Using the version below, Python complained
  about the line 
. M[ -1 , : ] = -p[ : -1 ]
  So, in view of you comments about slicing in you follow-up,
  I tried without the slicing on the right 
.. M[ -1 , : ] = -p[ -1 ]
  The following code will run and produce results,
  but I'm wondering if I've totally screwed it up
  since the results I obtain are different from
  those obtained from the specific 5th order Numeric
  solution previously posted here 
. from numarray import *
.
. import numarray.linear_algebra as LA
.
. def monic( this_list ) :
.
. m  = [ ]
.
. last_item = this_list[ -1 ]
.
. for this_item in this_list :
.
. m.append( this_item / last_item )
.
. return m
.
.
. def roots( p ) :
.
. p = monic( p )
.
. n = len( p )   # degree of polynomial
.
. z = zeros( ( n , n ) )
.
. M = asarray( z , typecode = 'f8' )  # typecode = c16, complex
.
. M[ : -1 , 1 : ] = identity( n - 1 )
.
. M[ -1 , : ] = -p[ -1 ]# removed :  slicing on the right
.
. return LA.eigenvalues( M )
.
.
. coeff = [ 1. , 3. , 5. , 7. , 9. ]
.
. print 'Coefficients ..'
. print
. print '%s' % coeff
. print
. print 'Eigen Values .. '
. print
.
. eigen_values = roots( coeff )
.
. for this_value in eigen_values :
.
. print '%s' % this_value
.
Any clues would be greatly appreciated 
--
Stanley C. Kitching
Human Being
Phoenix, Arizona
--
http://mail.python.org/mailman/listinfo/python-list


Re: yield_all needed in Python

2005-03-01 Thread Douglas Alan
Andrew Dalke <[EMAIL PROTECTED]> writes:

> On Mon, 28 Feb 2005 18:25:51 -0500, Douglas Alan wrote:

>> While writing a generator, I was just thinking how Python needs a
>> "yield_all" statement.  With the help of Google, I found a
>> pre-existing discussion on this from a while back in the
>> Lightweight Languages mailing list.  I'll repost it here in order
>> to improve the chances of this enhancement actually happening
>> someday.

> You should also have looked for the responses to that. Tim Peter's
> response is available from

>   http://aspn.activestate.com/ASPN/Mail/Message/624273

[...]

> Here is the most relevant parts.

[...]

>BTW, Python almost never worries about worst-case behavior, and people
>using Python dicts instead of, e.g., balanced trees, get to carry their
>shame home with them hours earlier each day  .

If you'll reread what I wrote, you'll see that I'm not concerned with
performance, but rather my concern is that I want the syntactic sugar.
I'm tired of writing code that looks like

   def foogen(arg1):

  def foogen1(arg2):
 # Some code here

  # Some code here
  for e in foogen1(arg3): yield e
  # Some code here
  for e in foogen1(arg4): yield e
  # Some code here
  for e in foogen1(arg5): yield e  
  # Some code here
  for e in foogen1(arg6): yield e  

when it would be much prettier and easier to read if it looked like:

   def foogen(arg1):

  def foogen1(arg2):
 # Some code here

  # Some code here
  yield_all foogen1(arg3)
  # Some code here
  yield_all foogen1(arg4)
  # Some code here
  yield_all foogen1(arg5)
  # Some code here
  yield_all foogen1(arg6)

|>oug
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: yield_all needed in Python

2005-03-01 Thread Douglas Alan
"Terry Reedy" <[EMAIL PROTECTED]> writes:

> Cetainly, if  iterator> == , I don't see how anything
> is gained except for a few keystrokes.

What's gained is making one's code more readable and maintainable,
which is the one of the primary reasons that I use Python.

|>oug
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list of all type names

2005-03-01 Thread Peter Hansen
Peter Maas wrote:
I would avoid the use of generic names for variables but rather use
dict1 or aDict etc. If you want to avoid a name collision without
the use of naming conventions you could rename __builtins__:
bi = __builtins__
del __builtins__
Then you can define what you like but you will have to reference dict,
list etc. as bi.dict, bi.list, ...
Except that you should never access __builtins__, and the
module is actually called __builtin__.  See this thread
for what should probably be considered the canonical
comment on this topic:
http://groups.google.ca/groups?threadm=mailman.1021141460.1004.python-list%40python.org
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Canonical way of dealing with null-separated lines?

2005-03-01 Thread Douglas Alan
"John Machin" <[EMAIL PROTECTED]> writes:

>>lines = (partialLine + charsJustRead).split(newline)

> The above line is prepending a short string to what will typically be a
> whole buffer full. There's gotta be a better way to do it.

If there is, I'm all ears.  In a previous post I provided code that
doesn't concatinate any strings together until the last possible
moment (i.e. when yielding a value).  The problem with that the code
was that it was complicated and didn't work right in all cases.

One way of solving the string concatination issue would be to write a
string find routine that will work on lists of strings while ignoring
the boundaries between list elements.  (I.e., it will consider the
list of strings to be one long string for its purposes.)  Unless it is
written in C, however, I bet it will typically be much slower than the
code I just provided.

> Perhaps you might like to refer back to CdV's solution which was
> prepending the residue to the first element of the split() result.

The problem with that solution is that it doesn't work in all cases
when the line-separation string is more than one character.

>>for line in lines: yield line + outputLineEnd

> In the case of leaveNewline being false, you are concatenating an empty
> string. IMHO, to quote Jon Bentley, one should "do nothing gracefully".

In Python,

   longString + "" is longString

evaluates to True.  I don't know how you can do nothing more
gracefully than that.

|>oug
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: windows bat file question

2005-03-01 Thread Peter Hansen
Tom Willis wrote:
I figured it out. I just took the embedded python code that was in the
batch file distributed with it and put it in it's own module.
Really my question was how would this ever work? It seems to me to be
a little screwy, but it would be handy to know if this was some sort
of convention that I could take advantage of if I ever write something
substantial that would need to run on windoze.
It looks like it might have been an untested version of something
that should have been using "python %0 %*" at that line instead
of just "python %*".
Under Windows XP (and probably NT, but not 98) the %* means
"all arguments", but doesn't appear (in testing just now on
my own machine) to include the name of the batch file itself.
On the other hand, %0 does include the name of the batch file,
but unfortunately it's actually just the part that you typed,
as in "blah" instead of "blah.bat" if you executed the file
by typing just "blah" instead of "blah.bat".
All things considered, it does look like it could never have
worked properly, but Windows is freakish enough that there
might well be some sequence of events and set of conditions
under which it might actually work as intended...
Of course, if you're on XP where you could hope that the
%* magic could work at all, you can also just modify the
contents of the environment variable PATHEXT to include .py,
rename the script to .py and strip out all that crappy
BAT stuff, and run it as intended with (almost) no
complications.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: accessor/mutator functions

2005-03-01 Thread Nick Craig-Wood
Dan Sommers <[EMAIL PROTECTED]> wrote:
>  We used to have holy wars over the appropriate level of comments in
>  source code.

Well according to the refactoring book I just read (by Martin Fowler)
the appropriate level of comments is None.  If you see a comment you
should extract the complicated code into a method with a useful name,
or add well named intermediate variables, or add an assertion.

Its a point of view...  Not 100% sure I agree with it but I see where
he is coming from.  I like a doc-string per public method so pydoc
looks nice myself...

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: accessor/mutator functions

2005-03-01 Thread Carl Banks

Steve Holden wrote:
> Carl Banks wrote:
> > Don't use getattr and setattr unless you have to construct the name
of
> > the attribute at run time.  That's what they're for.
> >
> Well, they are surely helpful in delegation contexts as well, or do I

> misunderstand?

I consider that a degenerate form of constructing a name at run time.
:)

You're right: I should have said, "Don't use them unless you don't know
the name at programming time."


-- 
CARL BANKS

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


Re: assigning a custom mapping type to __dict__

2005-03-01 Thread Steven Bethard
Daniel Cer wrote:
Why not just inherit from dict? That seems to work.
Because that isn't the question - Steven knows how to make it work, what 
he's
curious about is why things are the way they are :)
Sorry, didn't mean to be a pest :)
I guess I assumed Steve already knew that he could inherit from dict.
That being said, I was wondering why pragmatically this wouldn't be the
right thing to do (in order to do what he seemed to want to do).
The problem with inheriting from dict is that you then need to override 
*all* the methods in the dict object, because they all go straight to 
Python's dict'c C code functions.  So just because you redefine 
__getitem__ doesn't mean you don't still have to redefine __contains__, 
get, update, etc.  UserDict.DictMixin can help with this some, but the 
ideal situation would be to only have to define the methods you actually 
support.  Inheriting from dict likely means you have to redefine a bunch 
of functions to raise Exceptions saying that they're unsupported.

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


reuse validation logic with descriptors

2005-03-01 Thread David S.
I am looking for a way to implement the same simple validation on many 
instance attributes and I thought descriptors
(http://users.rcn.com/python/download/Descriptor.htm) looked like the 
right tool.  

But I am confused by their behavior on instance of my class. 
I can only get the approximate behavior by using class variables.

I am looking for something like:

class SingleChar(object):
def init(self):
self._char = None

def __set__(self, instance, value):
if not len(value) == 1:
raise ValueError
self._char = value

def __get__(self, instance, owner):
return self._char
   
class Flags(object):
def __init__(self):
self.a = SingleChar()
self.b = SingleChar()

f = Flags()
f.a = "a"
f.b = "bb"
exceptions.ValueError
ValueError:

What I actually get when I try this is f.a and f.b become str instances.

Meanwhile, I can get this to work, except that a and b are now just class
attributes.

class CFlags(object):
a = SingleChar()
b = SingleChar()

What is the proper and clean way to accomplish this sort of thing, so that you
can reuse the logic in for many instance attributes across multiple classes?

Thanks, David S.

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


What's the cost of using hundreds of threads?

2005-03-01 Thread Przemysław Różycki
Hello,
I have written some code, which creates many threads for each connection 
('main connection'). The purpose of this code is to balance the load 
between several connections ('pipes'). The number of spawned threads 
depends on how many pipes I create (= 2*n+2, where n is the number of 
pipes).

For good results I'll presumably share main connection's load between 10 
pipes - therefore 22 threads will be spawned. Now if about 50 
connections are forwarded the number of threads rises to thousand of 
threads (or several thousands if even more connections are established).

My questions are:
- What is the cost (in memory / CPU usage) of creating such amounts of 
threads?
- Is there any 'upper boundary' that limits the number of threads? (is 
it python / OS related)
- Is that the sign of 'clumsy programming' - i.e. Is creating so many 
threads a bad habit? (I must say that it simplified the solution of my 
problem very much).

Limiting the number of threads is possible, but would affect the 
independence of data flows. (ok I admit - creating tricky algorithm 
could perhaps gurantee concurrency without spawning so many threads - 
but it's the simplest solution to this problem :) ).
--
http://mail.python.org/mailman/listinfo/python-list


Re: smtplib Segfaults Python under Debian

2005-03-01 Thread Cousin Stanley
| localhost:~alex#python
| Python 2.3.3 (#2, Feb 24 2004, 09:29:20)
| [GCC 3.3.3 (Debian)] on linux2
| Type "help", "copyright", "credits" or "license"
| for more information.
|
| >>> import smtplib
|
| Segmentation fault (core dumped)
|
| This happens under python 2.2 and 2.3 and 2.4
| 
Alex 
  Using Python 2.3.5 here under Debian GNU/Linux Sarge
  import smtplib is OK 
[EMAIL PROTECTED] :  ~/python  $ python
Python 2.3.5 (#2, Feb  9 2005, 00:38:15)
[GCC 3.3.5 (Debian 1:3.3.5-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import smtplib
>>>
>>> smtplib.__file__
'/usr/lib/python2.3/smtplib.pyc'
>>>
[EMAIL PROTECTED] :  ~/python  $ apt-cache policy python2.3
python2.3:
  Installed: 2.3.5-1
  Candidate: 2.3.5-1
  Version Table:
 *** 2.3.5-1 0
500 http://mirrors.kernel.org sarge/main Packages
100 /var/lib/dpkg/status
--
Stanley C. Kitching
Human Being
Phoenix, Arizona
--
http://mail.python.org/mailman/listinfo/python-list


Problem in Dictionaries

2005-03-01 Thread Glauco Silva

I´m with problem in Dictionaries !
I would like to know if the dictionary can sort with a function that i give to then!
Because i need to have a dictionary sort by key !
For exemple :
dict  = {}
dict[50] = "fifty"
dict[129] = "a hundred twenty nine"
print dict
{129: "a hundred twenty nine", 50: "fifty"}
 
But i need dict sort :
{ 50: "fifty", 129: "a hundred twenty nine"}
 
How can i do this ?
 
Thanks,
Glauco Buzini da Costa Silva

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

Re: class factory example needed (long)

2005-03-01 Thread Steven Bethard
Gary Ruben wrote:
OK, I've managed to get this to work with Rainer's method, but I 
realised it is not the best way to do it, since the methods are being 
added by the constructor, i.e. they are instance methods. This means 
that every time a foo object is created, a whole lot of code is being 
run. It would be better to do the same thing with class 'static' 
methods, if this is possible, so that the methods are created just once.
Is this possible?
See my comment on the recipe at:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/389793
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: yield_all needed in Python

2005-03-01 Thread Duncan Booth
Douglas Alan wrote:

> "Terry Reedy" <[EMAIL PROTECTED]> writes:
> 
>> Cetainly, if > iterator> == , I don't see how anything
>> is gained except for a few keystrokes.
> 
> What's gained is making one's code more readable and maintainable,
> which is the one of the primary reasons that I use Python.

On of the reasons why Python is readable is that the core language is 
comparatively small. Adding a new reserved word simply to save a few 
characters is a difficult choice, and each case has to be judged on its 
merits, but it seems to me that in this case the extra syntax is a burden 
that would have to be learned by all Python programmers with very little 
benefit.

Remember that many generators will want to do slightly more than just yield 
from another iterator, and the for loop allows you to put in additional 
processing easily whereas 'yield_all' has very limited application e.g.

   for tok in tokenstream():
   if tok.type != COMMENT:
   yield tok

I just scanned a random collection of my Python files: out of 50 yield 
statements I found only 3 which could be rewritten using yield_all.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why do descriptors (and thus properties) only work on attributes.

2005-03-01 Thread Steven Bethard
Steve Holden wrote:
Steven Bethard wrote:
Antoon Pardon wrote:
Can anyone explain why descriptors only work when they are an attribute
to an object or class.  I think a lot of interesting things one can
do with descriptors would be just as interesting if the object stood
on itself instead of being an attribute to an other object.
Not sure what "stood on itself" really means, but if you just want to 
be able to have module-level properties, you can do something like:

Think in non-English (stand outside yourself?) for a second, rememberinf 
Antoon is Belgian (if you knew that):

   "on" => "by"
   "stood on itself" => "stood by itself"
 => "standalone"
Sorry, I gathered that this meant "standalone".  My problem was that I'm 
not sure what "standalone" means in the context of descriptors. 
Descriptors are invoked when dotted-attribute access is used.  When 
exactly is he proposing "standalone" descriptors would be invoked?

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


ListMixin (WAS: How do you control _all_ items added to a list?)

2005-03-01 Thread Steven Bethard
Nick Coghlan wrote:
> Hmm, it might be nice if there was a UserList.ListMixin that was the
> counterpart to UserDict.DictMixin
I've thought this occasionally too.  One of the tricky issues though is 
that often you'd like to define __getitem__ for single items and have 
ListMixin add the code for slices.  I haven't figured out how to do this 
cleanly yet...

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


Re: Decimal, __radd__, and custom numeric types...

2005-03-01 Thread Blake T. Garretson
Thanks for the suggestions and modified module.  I will probably just
use this "fixed" module to solve my immediate problem.  I appreciate
your post to python-dev as well; it looks like this may be addressed in
a future release. :)

Thanks,
Blake

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


Re: reuse validation logic with descriptors

2005-03-01 Thread Steven Bethard
David S. wrote:
I am looking for a way to implement the same simple validation on many 
instance attributes and I thought descriptors
(http://users.rcn.com/python/download/Descriptor.htm) looked like the 
right tool.  

But I am confused by their behavior on instance of my class. 
I can only get the approximate behavior by using class variables.

I am looking for something like:
class SingleChar(object):
def init(self):
self._char = None
def __set__(self, instance, value):
if not len(value) == 1:
raise ValueError
self._char = value
def __get__(self, instance, owner):
return self._char
   
class Flags(object):
def __init__(self):
self.a = SingleChar()
self.b = SingleChar()

f = Flags()
f.a = "a"
f.b = "bb"
exceptions.ValueError
ValueError:

What I actually get when I try this is f.a and f.b become str instances.
Meanwhile, I can get this to work, except that a and b are now just class
attributes.
class CFlags(object):
a = SingleChar()
b = SingleChar()
What is the proper and clean way to accomplish this sort of thing, so that you
can reuse the logic in for many instance attributes across multiple classes?
Looks like you're trying to reinvent the property descriptor.  Try using 
the builtin property instead:

py> def getchar(self):
... if not hasattr(self, '_char'):
... self._char = None
... return self._char
...
py> def setchar(self, value):
... if not len(value) == 1:
... raise ValueError
... self._char = value
...
py> singlechar = property(getchar, setchar)
py> class Flags(object):
... a = singlechar
... b = singlechar
...
py> f = Flags()
py> f.a = "a"
py> f.b = "bb"
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 3, in setchar
ValueError
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: yield_all needed in Python

2005-03-01 Thread Douglas Alan
Duncan Booth <[EMAIL PROTECTED]> writes:

> Douglas Alan wrote:

>> "Terry Reedy" <[EMAIL PROTECTED]> writes:

>>> Cetainly, if >> iterator> == , I don't see how anything
>>> is gained except for a few keystrokes.

>> What's gained is making one's code more readable and maintainable,
>> which is the one of the primary reasons that I use Python.

> On of the reasons why Python is readable is that the core language is 
> comparatively small.

It's not that small anymore.  What it *is* is relatively conceptually
simple and readily comprehensible (i.e. "lightweight"), unlike
languages like C++ and Perl.

> Adding a new reserved word simply to save a few 
> characters

It's not to "save a few characters".  It's to make it immediately
clear what is happening.

> is a difficult choice, and each case has to be judged on its merits,
> but it seems to me that in this case the extra syntax is a burden
> that would have to be learned by all Python programmers with very
> little benefit.

The amount of effort to learn what "yield_all" does compared to the
amount of effort to understand generators in general is so miniscule,
as to be negligible.  Besides, by this argument, the standard library
should be kept as small as possible too, since people have to learn
all that stuff in order to understand someone else's code.

> Remember that many generators will want to do slightly more than just yield 
> from another iterator, and the for loop allows you to put in additional 
> processing easily whereas 'yield_all' has very limited application e.g.

>for tok in tokenstream():
>if tok.type != COMMENT:
>yield tok

> I just scanned a random collection of my Python files: out of 50 yield 
> statements I found only 3 which could be rewritten using yield_all.

For me, it's a matter of providing the ability to implement
subroutines elegantly within generators.  Without yield_all, it is not
elegent at all to use subroutines to do some of the yielding, since
the calls to the subroutines are complex, verbose statements, rather
than simple ones.

I vote for the ability to have elegant, readable subroutining,
regardless of how much you in particular would use it.

|>oug
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >