Python on Linux Cluster

2004-12-22 Thread Gurpreet Sachdeva
I have shifted my python script on a 4 node open ssi cluster. Please
guide me what changes do I have to do in my python scripts to fully
utilize the cluster. How do we introduce parralel processing in
python???

-- 
Thanks and Regards,
GSS
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PHP vs. Python

2004-12-22 Thread Fredrik Lundh
Paul Rubin wrote:

>> But pure speed is not the all. Python can scale better,
>
> If a system is fast enough on a single processor, it doesn't need to scale.

the word "scale" doesn't necessarily imply performance.  software developers
also deal with scales like program size, application complexity, team size, 
number
of external systems, etc.

 



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


Re: list IndexError

2004-12-22 Thread Ishwor
On Thu, 23 Dec 2004 08:35:57 +0100, Fredrik Lundh
<[EMAIL PROTECTED]> wrote:
> Mike C. Fletcher wrote:
> 
> >>yeah actually i saw what Fedrik had to say above. I created a sliced
> >>copy of the l & did my homework within the for loop
> >>
> > You might want to check it again before you hand it in ;) ...
> >
> > >>> def ishwor( source ):
> > ---for item in source:
> >+++  for item in source[:]:
  if item == 'd':
> > ...source.remove( item )
> 
> that's not the code he quoted in the mail you replied to, though...
> 
;-)

[snip]

-- 
cheers,
Ishwor Gurung
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-22 Thread Craig Ringer
On Thu, 2004-12-23 at 15:21, [EMAIL PROTECTED] wrote:
> This is NOT true. Functional programming, AFAIKC, is a cool thing, and
> in-fashion, increases productivity & readability, and an indispensable
> thing for a flexible scripting lang.

Couldn't agree more. One of the things I find most valuable about Python
is the ability to use functional style where it's the most appropriate
tool to solve a problem - WITHOUT being locked into a pure-functional
purist language where I have to fight the language to get other things
done.

> The inline/lambda function is
> feature is shared by many lang. which I frequently use,
> MATLAB/R/Python/etc. Well, you can say apply() is 'deprecated' now,
> (which is another functional thing I like), but I am still using it. I
> am not a desperate person who uses higher-order function factory a lot,
> but if lambda keyword is removed, I swear I will not use the python
> anymore.

I also make signficant use of Lambda functions, but less than I used to.
I've recently realised that they don't fit too well with Python's
indentation-is-significant syntax, and that in many cases my code is
much more readable through the use of a local def rather than a lambda.

In other words, I increasingly find that I prefer:

def myfunction(x):
return x**4
def mysecondfuntion(x):
return (x * 4 + x**2) / x
make_some_call(myfunction, mysecondfunction)

to:

make_some_call( lambda x: x**4, lambda x: (x * 4 + x**2) / x)

finding the former more readable. The function names are after all just
temporary local bindings of the function object to the name - no big
deal. Both the temporary function and the lambda can be used as
closures, have no impact outside the local function's scope, etc. I'd be
interested to know if there's anything more to it than this (with the
side note that just don't care if my temporary functions are anonymous
or not).

One of the things I love about Python is the ability to mix functional,
OO, and procedural style as appropriate. I can write a whole bunch of
functions that just return the result of list comprehensions, then use
them to operate on instances of an object from a procedural style main
function. In fact, that's often the cleanest way to solve the problem.
The fact that I have that option is something I really like.

As for apply(), while it is gone, the f(*args) extension syntax is now
available so I don't really see the issue. After all, these two are the
same:

def callfunc(function,args):
return apply(function,args)

and

def callfunc(function,args):
return function(*args)

its just an (IMO trivial) difference in syntax. I'd be interested in
knowing if there is in fact more to it than this.

--
Craig Ringer

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


Re: Newbie namespace question

2004-12-22 Thread Nick Coghlan
Brandon wrote:
Peter,
You're correct about the bug.  I did need a 'self' parm...  I was just
winging the example because the actual code is pretty large.  I'm using
google groups for my posting and it didn't carry spaces through (I did
use spaces and not tabs).
The "fix" or workaround was to import __builtin__ and add the
AdminConfig reference there in configure_server_foo.py as follows:
import __builtin__
__builtin__.AdminConfig = AdminConfig
As for the indentations, substitute ~ with a space.
Hopefully, a bug free and "indented" version.  :)
#jdbc.py
class DataSource:
~~~def __init__(self, servername):
~~self.servername = servername
~~~def create(self, name, connectionInfo, etc):
~~#Call the IBM supplied WebSphere config object
~~AdminConfig.create('DataSource')
Is there any particular reason DataSource can't be modified to accept a 
reference to the AdminConfig as a constructor argument? Or as a class attribute?

Alternatively, here's another trick to 'nicely' set a module global from outside 
a module:

#jdbc.py
def setAdminConfig(adm_cfg):
  global AdminConfig
  AdminConfig = adm_cfg
However, if you would prefer not to alter jdbc.py, consider trying:
import jdbc
jdbc.AdminConfig = AdminConfig
Global variables are bad karma to start with, and monkeying with __builtin__ is 
even worse :)

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


Re: Lambda going out of fashion

2004-12-22 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
Well, you can say apply() is 'deprecated' now,
(which is another functional thing I like), but I am still using it.
Interesting.  Could you explain why?  Personally, I find the 
*expr/**expr syntax much simpler, so I'd be interested in knowing what 
motivates you to continue to use apply...

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


Re: list IndexError

2004-12-22 Thread Fredrik Lundh
Mike C. Fletcher wrote:

>>yeah actually i saw what Fedrik had to say above. I created a sliced
>>copy of the l & did my homework within the for loop
>>
> You might want to check it again before you hand it in ;) ...
>
> >>> def ishwor( source ):
> ... for item in source:
> ... if item == 'd':
> ... source.remove( item )

that's not the code he quoted in the mail you replied to, though...

 



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


Re: Lambda going out of fashion

2004-12-22 Thread Craig Ringer
On Thu, 2004-12-23 at 12:47, Keith Dart wrote:
> On 2004-12-23, Stephen Thorne <[EMAIL PROTECTED]> wrote:
> > Hi guys,
> >
> > I'm a little worried about the expected disappearance of lambda in
> > python3000. I've had my brain badly broken by functional programming
> > in the past, and I would hate to see things suddenly become harder
> > than they need to be.
> 
> I use Python lambda quite a bit, and I don't understand the recent noise
> about problems with it, and its removal. I don't have a problem with
> lambdas.
> 
> My personal gripe is this. I think the core language, as of 2.3 or 2.4
> is very good, has more features than most people will ever use, and they
> (Guido, et al.) can stop tinkering with it now and concentrate more on
> the standard libraries. 

As someone working with the Python/C API, I'd have to argue that the
Python language may (I express no opinion on this) be "Done", but
CPython doesn't look like it is.

In my view a bunch of minor, but irritating, issues exist:

  It's hard to consistently support Unicode in extension modules without
doing a lot of jumping through hoops. Unicode in docstrings is
particularly painful. This may not be a big deal for normal extension
modules, but when embedding Python it's a source of considerable
frustration. It's also not easy to make docstrings translatable.
Supporting an optional encoding argument for docstrings in the
PyMethodDef struct would help a lot, especially for docstrings returned
by translation mechanisms.

  Py_NewInterpreter/Py_EndInterpreter used in the main thread doesn't
work with a threaded Python debug build, calling abort(). If a
non-threaded Python is used, or a non-debug build, they appear to work
fine. There are some indications on the mailing list that this is due to
Python's reliance on thread-local-storage for per-interpreter data, but
there are no suggestions on how to work around this or even solid
explanations of it. This sucks severely when embedding Python in Qt
applications, as GUI calls may only be made from the main thread but
subinterepreters may not be created in the main thread. It'd be
fantastic if the subinterpreter mechanism could be fleshed out a bit. I
looked at it, but my C voodo just isn't up there. The ability to run
scripts in private interpreters or subinterpreters (that are disposed of
when the script terminates) would be immensely useful when using Python
as a powerful glue/scripting language in GUI apps.

  IMO the reference behaviour of functions in the C API could be
clearer. One often has to simply know, or refer to the docs, to tell
whether a particular call steals a reference or is reference neutral.
Take, for example, PyDict_SetItemString vs PyMapping_SetItemString . Is
it obvious that one of those steals a reference, and one is reference
neutral? Is there any obvious rationale behind this? I'm not overflowing
with useful suggestions about this, but I do think it'd be nice if there
was a way to more easily tell how functions behave in regard to
reference counts.

  Const. I know there's a whole giant can of worms here, but even so -
some parts of the Python/C API take arguments that will almost always be
string literals, such as format values for Py_BuildValue and
PyArg_ParseTuple or the string arguments to Py*_(Get|Set)String calls.
Many of these are not declared const, though they're not passed on to
anywhere else. This means that especially in c++, one ends up doing a
lot of swearing and including a lot of ugly and unnecessary string
copies or const_cast()s to silence the compiler's whining. It
would be nice if functions in the Python/C API would declare arguments
(not return values) const if they do not pass them on and do not change
them.

Of course, all these are just my opinion in the end, but I'd still have
to argue that using Python from C could be a lot nicer than it is. The
API is still pretty good, but the solution of these issues would make it
a fair bit nicer again, especially for people embedding Python in apps
(a place were it can seriously excel as a scripting/extension/glue
language).

--
Craig Ringer

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


Re: Lambda going out of fashion

2004-12-22 Thread tanghaibao
This is NOT true. Functional programming, AFAIKC, is a cool thing, and
in-fashion, increases productivity & readability, and an indispensable
thing for a flexible scripting lang. The inline/lambda function is
feature is shared by many lang. which I frequently use,
MATLAB/R/Python/etc. Well, you can say apply() is 'deprecated' now,
(which is another functional thing I like), but I am still using it. I
am not a desperate person who uses higher-order function factory a lot,
but if lambda keyword is removed, I swear I will not use the python
anymore.

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


Re: A rational proposal

2004-12-22 Thread Nick Coghlan
Mike Meyer wrote:
Actually, I suggested that:
float() + Rational() returns float
You're suggesting that the implicit conversion to float not happen
here, and the user be forced to cast it to float? And you're saying
Decimal does it that way.[
Yup.
I had another look at PEP 327 (the section on implicit construction) and the 
reasoning that got us to that behaviour wasn't quite what I thought. However, I 
think the point still holds for Rational - the conversion often won't be exact 
in either direction, so it's OK for Python to ask the programmer to confirm that 
they really want to make the conversion.

I think adding subsections modelled on PEP 327's "Explicit construction", 
"Implicit construction" and "Python usability" would be a big plus for the new 
Rational PEP. The layout Facundo used makes it obvious that issues of playing 
well with other types have been considered properly.

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


Re: The limitation of the Photon Hypothesis

2004-12-22 Thread Erik Max Francis
[EMAIL PROTECTED] wrote:
I definitely have no rights to judge this article but I have a vague
idea that this fine article goes to a wrong place. Except that the
topic thing is symbolically related: Photon hYpoTHesis limitatiON.
It's a well-known and persistent crank.
--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
  Describe a circle, stroke its back and it turns vicious.
  -- Ionesco
--
http://mail.python.org/mailman/listinfo/python-list


Re: The limitation of the Photon Hypothesis

2004-12-22 Thread tanghaibao
I definitely have no rights to judge this article but I have a vague
idea that this fine article goes to a wrong place. Except that the
topic thing is symbolically related: Photon hYpoTHesis limitatiON.

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


Re: PHP vs. Python

2004-12-22 Thread Craig Ringer
On Thu, 2004-12-23 at 06:03, [EMAIL PROTECTED] wrote:
> Anyone know which is faster?  I'm a PHP programmer but considering
> getting into Python ... did searches on Google but didn't turn much up
> on this.

Others have answered interpretations of your question other than
execution speed. I can't give you numbers on that - you'd probably have
to do some benchmarks yourself - but can offer a few suggestions.

First, Python can be _seriously_ fast for web use. You need to make sure
you're not starting and terminating interpreters all the time, so you'll
need to use a Python embedded web server proxied by Apache (like Zope
does), SCGI (as works well with Quixote), Twisted, or some other way of
running your code persistently. Persistent CGI usually means worrying
about memory leaks, but unless you're using flakey C extension modules
that shouldn't be a problem with Python.

If you have your Python code running as some sort of persistent server,
then you can use tools like Psyco to get a further (often very
impressive) speed boost. The biggest speed-up with Pysco that I've
clocked is 20x, but 3x - 5x is fairly common.

Whether it'll be faster or slower than PHP, I just can't guess. I think
it'd certainly be well worth a try, especially if you're writing any
more complex applications.

That said, for 90% of users development time matters more than execution
speed, and that's another matter entirely.

--
Craig Ringer

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


Re: Killing a python thread with a signal

2004-12-22 Thread Craig Ringer
On Thu, 2004-12-23 at 04:51, James Lamanna wrote:
> So I've created a thread with the threading.Thread class, but I want to 
> be able to kill this thread because it does a select() with a timeout of 
> None.

I recall seeing various discussion of signals and threading on the list
in the past - it might be a good idea to search the archives.

--
Craig Ringer

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


Re: Lambda going out of fashion

2004-12-22 Thread Steven Bethard
Stephen Thorne wrote:
{
 'one': lambda x:x.blat(),
 'two': lambda x:x.blah(),
}.get(someValue, lambda x:0)(someOtherValue)
The alternatives to this, reletively simple pattern, which is a rough
parallel to the 'switch' statement in C, involve creating named
functions, and remove the code from the context it is to be called
from (my major gripe).
Here's what my code for a very similar situation usually looks like:
py> class Foo(object):
... def blat(self):
... print "blat"
... def blah(self):
... print "blah"
...
py> key, foo = 'two', Foo()
py> try:
... result = dict(one=Foo.blat, two=Foo.blah)[key](foo)
... except KeyError:
... result = 0
...
blah
As you can see, I just use the unbound methods of the parent class 
directly.  Of course this means that your code won't work if 'foo' isn't 
actually a Foo instance.  So you lose a little generality, but you gain 
a bit in conciceness of expression (IMHO).  Note also that I don't use 
dict.get, relying on the KeyError instead.  Usually, my case for when no 
function applies is complex enough to not be expressable in a lambda 
anyway, so this is generally more appropriate for my code.

While I don't generally find that I need lambda, I'm not particularly 
arguing against it here.  I just thought it might be helpful to 
demonstrate how this code might be written concicely without lambdas.

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


Re: Mutable objects which define __hash__ (was Re: Why are tuples immutable?)

2004-12-22 Thread Nick Coghlan
Steven Bethard wrote:
Of course, if rehash worked in place, you could probably do some 
optimizations to only rehash the necessary items.
Yep, especially given this little critter from dictobject.h which contains 
everything needed to spot mutated objects:

typedef struct {
long me_hash;  /* cached hash code of me_key */
PyObject *me_key;
PyObject *me_value;
} PyDictEntry;
So the major downside to giving standard mutable objects hash methods is that 
dictionaries then suffer from the 'mutation without resorting' problem that 
sorted lists can currently suffer from.

As I said to Antoon, I no longer have any theoretical objection to the idea of 
mutable objects with a variable hash. I do, however, have a practical objection 
- mutating a dict's keys without calling rehash() could lead to some extremely 
subtle bugs that the interpreter can't really help identify. It just seems far 
too easy to inadvertently burn yourself by altering an object that is being used 
as a dictionary key.

What I'd prefer to see is a collections.id_dict (and a corresponding 
collections.id_set) - identity based versions of the standard classes, useful 
when classifying mutable objects. The id_dict would be handy when you want to 
associate additional information with a mutable object without altering the 
object (e.g. analysing a graph, and recording extra information about each of 
the nodes).

For mutable objects, value-based keying doesn't really make sense (as the value 
may change with time), but identity-based keying is entirely straightforward, 
and including ID-based dicts and sets would go a long way to providing OOWTDI. 
And the performance should leave the Python-based versions for dead. They should 
actually be slightly faster than the standard dict() and set(), since they don't 
have to deal with user-overridable special methods :)

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


The limitation of the Photon Hypothesis

2004-12-22 Thread bill
 
 

The limitation of the Photon Hypothesis

 

According to the electromagnetic theory of light, its energy is related to the 
amplitude of the electric field of the electromagnetic wave, W=eE^2V(where E is 
the amplitude and V is the volume). It apparently has nothing to do with the 
light's frequency f. 

To explain the photoelectric effect, Einstein put forward the photon 
hypothesis. His paper hypothesized light was made of quantum packets of energy 
called photons. Each photon carried a specific energy related to its frequency 
f, W=hf. This has nothing to do with the amplitude of the electromagnetic wave 
E. 

For the electromagnetic wave that the amplitude E has nothing to do with the 
light's frequency f, if the light's frequency f is high enough, the energy of 
the photon in light is greater than the light's energy, hf>eE^2V. Apparently, 
this is incompatible with the electromagnetic theory of light.

THE UNCERTAINTY PRINCIPLE IS UNTENABLE

 

By re-analysing Heisenberg's Gamma-Ray Microscope experiment and one of the 
thought experiment from which the uncertainty principle is demonstrated, it is 
actually found that the uncertainty principle cannot be demonstrated by them. 
It is therefore found to be untenable.

Key words: 
uncertainty principle; Heisenberg's Gamma-Ray Microscope Experiment; thought 
experiment 

 

The History Of The Uncertainty Principle

If one wants to be clear about what is meant by "position of an object," for 
example of an electron., then one has to specify definite experiments by which 
the "position of an electron" can be measured; otherwise this term has no 
meaning at all. --Heisenberg, in uncertainty paper, 1927

Are the uncertainty relations that Heisenberg discovered in 1927 just the 
result of the equations used, or are they really built into every measurement? 
Heisenberg turned to a thought experiment, since he believed that all concepts 
in science require a definition based on actual, or possible, experimental 
observations.

Heisenberg pictured a microscope that obtains very high resolution by using 
high-energy gamma rays for illumination. No such microscope exists at present, 
but it could be constructed in principle. Heisenberg imagined using this 
microscope to see an electron and to measure its position. He found that the 
electron's position and momentum did indeed obey the uncertainty relation he 
had derived mathematically. Bohr pointed out some flaws in the experiment, but 
once these were corrected the demonstration was fully convincing. 

 

Thought Experiment 1

The corrected version of the thought experiment

Heisenberg's Gamma-Ray Microscope Experiment


A free electron sits directly beneath the center of the microscope's lens 
(please see AIP page http://www.aip.org/history/heisenberg/p08b.htm or diagram 
below) . The circular lens forms a cone of angle 2A from the electron. The 
electron is then illuminated from the left by gamma rays--high-energy light 
which has the shortest wavelength. These yield the highest resolution, for 
according to a principle of wave optics, the microscope can resolve (that is, 
"see" or distinguish) objects to a size of dx, which is related to and to the 
wavelength L of the gamma ray, by the expression: 

dx = L/(2sinA) (1) 

However, in quantum mechanics, where a light wave can act like a particle, a 
gamma ray striking an electron gives it a kick. At the moment the light is 
diffracted by the electron into the microscope lens, the electron is thrust to 
the right. To be observed by the microscope, the gamma ray must be scattered 
into any angle within the cone of angle 2A. In quantum mechanics, the gamma ray 
carries momentum as if it were a particle. The total momentum p is related to 
the wavelength by the formula, 

p = h / L, where h is Planck's constant. (2) 

In the extreme case of diffraction of the gamma ray to the right edge of the 
lens, the total momentum would be the sum of the electron's momentum P'x in the 
x direction and the gamma ray's momentum in the x direction: 

P' x + (h sinA) / L', where L' is the wavelength of the deflected gamma ray. 

In the other extreme, the observed gamma ray recoils backward, just hitting the 
left edge of the lens. In this case, the total momentum in the X direction is: 

P''x - (h sinA) / L''. 

The final x momentum in each case must equal the initial X momentum, since 
momentum is conserved. Therefore, the final X moment are equal to each other: 

P'x + (h sinA) / L' = P''x - (h sinA) / L'' (3) 

If A is small, then the wavelengths are approximately the same, 

L' ~ L" ~ L. So we have 

P''x - P'x = dPx ~ 2h sinA / L (4) 

Since dx = L/(2 sinA), we obtain a reciprocal relationship between the minimum 
uncertainty in the measured position, dx, of the electron along the X axis and 
the uncertainty in its momentum, dPx, in the x direction: 

dPx ~ h / dx or dPx dx ~ h. (5) 

For more than minimum uncertainty, the "greater than" sign may added. 

Except for the fa

Re: Mutable objects which define __hash__ (was Re: Why are tuples immutable?)

2004-12-22 Thread Nick Coghlan
Jeff Shannon wrote:
To be honest, given how easy it is to key a current dict off of object 
id, I don't see much real value in creating a separate dict type that 
does it by default.  But as long as it's an addition, rather than a 
change to existing behavior, then the only real problem with it is the 
standard "makes the language bigger".
Something which used different behaviour at C-level could be a fair bit faster, 
since it wouldn't have to jump back into the eval loop all the time when looking 
up the hash or comparison functions. Passing id() into the dictionary isn't so 
good either, as you have to make the function call on every item lookup, and you 
can't effectively iterate over the contents of the dictionary.

Its utility might be more obvious as a set variant rather than a dictionary 
variant, though, as the best use I can see for it is in using sets to classify 
mutable objects like lists (such as Antoon's example of applying special 
processing to certain graph points).

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


effbot TidyHTMLTreeBuilder problem

2004-12-22 Thread dayzman
Hi all,

I'm using TidyHTMLTreeBuilder to model syntax structure of HTML
documents. I've been trying to feed in Yahoo and CNN, but the parser
seems to crash:

"  File
"C:\Python23\Lib\site-packages\elementtidy\TidyHTMLTreeBuilder.py",
line 89, in parse
return ElementTree.parse(source, TreeBuilder())
File "C:\Python23\lib\site-packages\elementtree\ElementTree.py", line
865, in parse
tree.parse(source, parser)
File "C:\Python23\lib\site-packages\elementtree\ElementTree.py", line
590, in parse
self._root = parser.close()
File
"C:\Python23\Lib\site-packages\elementtidy\TidyHTMLTreeBuilder.py",
line 75, in close
return ElementTree.XML(stdout)
File "C:\Python23\lib\site-packages\elementtree\ElementTree.py", line
879, in XML
return parser.close()
File "C:\Python23\lib\site-packages\elementtree\ElementTree.py", line
1169, in close
self._parser.Parse("", 1) # end of data
ExpatError: no element found: line 1, column 0"

Could someone else please try it on their system and see if they also
have the same problem? I suspect this problem relates to  inside
.

Thank you very much for any help.

Cheers,
Michael

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


Re: PHP vs. Python

2004-12-22 Thread Eric Pederson
Paul Rubin did say:

> For sites that get less traffic than that, they only reason they need
> to scale if they're written in Python is that Python is too slow.


Asked earnestly: is there a feel or quantification that Python is slower than 
PHP in network applications?

If, so, I am wondering if it is because of the traction PHP has in the web 
community leading to possibly tighter integration with (e.g.) Apache.

My beloved Python-oriented webhost doesn't currently support Mod-Python due to 
concerns about unknown security risks, and without that one carries the 
interpreter start-up burden for each invocation, as I understand it.  Speed in 
a server-client environment does concern me a bit because 100+ hits per second 
would be the minimum realm of success for the web app I am building in Python 
(I do not foresee using PHP, so maybe I would convert everything to C++ if I 
had to, but I really would not want to have to...)

In everything I have done so far, Python's speed has been quite satisfactory, 
and I always remember the loud complainings in the MySQL forum about SQL 
queries that take seconds, minutes, days... only to end up magnitudes faster 
when someone points out the folly of the code or table set-up.

Not sure if the OP is considering Python v.s. PHP on the server or on the 
desktop (PHP isn't web only, except by common use); they are very different use 
cases.




Eric Pederson
http://www.songzilla.blogspot.com
:::
domainNot="@something.com"
domainIs=domainNot.replace("s","z")
ePrefix="".join([chr(ord(x)+1) for x in "do"])
mailMeAt=ePrefix+domainIs
:::

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


Re: mathmatical expressions evaluation

2004-12-22 Thread Tonino
thanks all for the info - and yes - speed is not really an issue and no
- it is not an implementation of a complete financial system - but
rather a small subset of a investment portfolio management system
developed by "another company" ...

What I am trying to achieve is to parse a formula(s) and generate a
result ...

I will look into the pyparsing suggested and maybe even leave out
numarrays for now - as it seems a bit overkill ...

The formula are a bit complex and maybe even difficult to write out
Thanks all - I will post my progress ;)

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


Re: Lambda going out of fashion

2004-12-22 Thread Keith Dart
On 2004-12-23, Stephen Thorne <[EMAIL PROTECTED]> wrote:
> Hi guys,
>
> I'm a little worried about the expected disappearance of lambda in
> python3000. I've had my brain badly broken by functional programming
> in the past, and I would hate to see things suddenly become harder
> than they need to be.

I use Python lambda quite a bit, and I don't understand the recent noise
about problems with it, and its removal. I don't have a problem with
lambdas.

My personal gripe is this. I think the core language, as of 2.3 or 2.4
is very good, has more features than most people will ever use, and they
(Guido, et al.) can stop tinkering with it now and concentrate more on
the standard libraries. 


-- 
-- ~
   Keith Dart <[EMAIL PROTECTED]>
   public key: ID: F3D288E4
   =
-- 
http://mail.python.org/mailman/listinfo/python-list


time zone

2004-12-22 Thread Kiran Vasu

how to set my mails recieving time to my local time(i am in malaysia)



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


Re: Howto Extract PNG from binary file @ 0x80?

2004-12-22 Thread Aaron
On Sat, 11 Dec 2004 10:53:19 +0100, Fredrik Lundh wrote:

> "flamesrock" <[EMAIL PROTECTED]> wrote:
> 
>> As a newbie to the language, I have no idea where to start..please bare
>> with me..
>>
>> The simcity 4 savegame file has a png image stored at the hex location
>> 0x80. What I want to extract it and create a file with the .png
>> extension in that directory.
>>
>> Can somebody explain with a snippet of code how I would accomplish
>> this? I've looked around but the information is too vague and I don't
>> know how to start.
> 
> there are *many* ways to ignore the first 128 bytes when you read a file
> (you can seek to the right location, you can read 128 bytes and throw them
> a way, you can read one byte 128 times and throw each one of them away,
> you can read all data and remove the first 128 bytes, etc).
> 
> here's a snippet that understands the structure of the PNG, and stops copying
> when it reaches the end of the PNG:
> 
> import struct
> 
> def pngcopy(infile, outfile):
> 
> # copy header
> header = infile.read(8)
> if header != "\211PNG\r\n\032\n":
> raise IOError("not a valid PNG file")
> outfile.write(header)
> 
> # copy chunks, until IEND
> while 1:
> chunk = infile.read(8)
> size, cid = struct.unpack("!l4s", chunk)
> outfile.write(chunk)
> outfile.write(infile.read(size))
> outfile.write(infile.read(4)) # checksum
> if cid == "IEND":
> break
> 
> to use this, open the input file (the simcity file) and the output file
> (the png file you want to create) in binary mode, use the "seek"
> method to move to the right place in the simcity file, and call "pngcopy"
> with the two file objects.
> 
> infile = open("mysimcityfile", "rb")
> infile.seek(0x80)
> outfile = open("myimage.png", "wb")
> pngcopy(infile, outfile)
> outfile.close()
> infile.close()
> 
> hope this helps!
> 
> 

Thanks! And what a pleasant surprise! I just noticed you authored the book
I've been studying - Python Standard Library. Its awesome ;)

Oh- and Sorry for the late response. Google groups wouldn't allow me to
followup. I'm using pan now.

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


Lambda going out of fashion

2004-12-22 Thread Stephen Thorne
Hi guys,

I'm a little worried about the expected disappearance of lambda in
python3000. I've had my brain badly broken by functional programming
in the past, and I would hate to see things suddenly become harder
than they need to be.

An example of what I mean is a quick script I wrote for doing certain
actions based on a regexp, which I will simlify in this instance to
make the pertanant points more relevent.

{
 'one': lambda x:x.blat(),
 'two': lambda x:x.blah(),
}.get(someValue, lambda x:0)(someOtherValue)

The alternatives to this, reletively simple pattern, which is a rough
parallel to the 'switch' statement in C, involve creating named
functions, and remove the code from the context it is to be called
from (my major gripe).

So, the questions I am asking are: 
Is this okay with everyone? 
Does anyone else feel that lambda is useful in this kind of context? 
Are there alternatives I have not considered?

merrily-yr's
Stephen.
-- 
http://mail.python.org/mailman/listinfo/python-list


Weekly Python Patch/Bug Summary

2004-12-22 Thread Kurt B. Kaiser
Patch / Bug Summary
___

Patches :  257 open ( -2) /  2715 closed ( +8) /  2972 total ( +6)
Bugs:  807 open (-15) /  4717 closed (+32) /  5524 total (+17)
RFE :  163 open ( +3) /   139 closed ( +0) /   302 total ( +3)

New / Reopened Patches
__

sgmllib.SGMLParser does not unescape attribute values; patch  (2004-12-18)
   http://python.org/sf/1087808  opened by  Titus Brown

Patch for bug 1088077  (2004-12-19)
   http://python.org/sf/1088078  opened by  Mike Meyer

msi.py patch to build mingw library  (2004-12-20)
CLOSED http://python.org/sf/1088716  opened by  Paul Moore

acknowledge signals in non-main threads  (2004-12-21)
   http://python.org/sf/1088832  opened by  Andrew Langmead

Patches Closed
__

CGIHTTPServer can't redirect  (2004-10-27)
   http://python.org/sf/1055159  closed by  jhylton

urllib2 HTTP digest authentication fix  (2004-09-30)
   http://python.org/sf/1037974  closed by  jhylton

fix bsddb memory leaks  (2004-06-06)
   http://python.org/sf/967763  closed by  greg

fast dictionary lookup by name  (2002-09-07)
   http://python.org/sf/606098  closed by  rhettinger

add time elapsed to gc debug output  (2003-06-26)
   http://python.org/sf/760990  closed by  rhettinger

Argument passing from /usr/bin/idle2.3 to idle.py  (2003-11-30)
   http://python.org/sf/851459  closed by  jafo

fix bug in StringIO.truncate - length not changed  (2004-05-11)
   http://python.org/sf/951915  closed by  rhettinger

msi.py patch to build mingw library  (2004-12-21)
   http://python.org/sf/1088716  closed by  loewis

New / Reopened Bugs
___

inspect.py module  (2004-12-18)
CLOSED http://python.org/sf/1087551  opened by  sprasanna199

mmap instance method access bug  (2004-12-18)
   http://python.org/sf/1087735  opened by  Josiah Carlson

Mac: make frameworkinstall skips docs, scripts  (2004-12-19)
   http://python.org/sf/1087737  opened by  Jack Jansen

example code not working  (2004-12-19)
CLOSED http://python.org/sf/1087975  opened by  perica

CGIHTTPServer: directories/scripts with spaces in their name  (2004-12-19)
   http://python.org/sf/1088039  opened by  LT

[PATCH] tty needs a way to restore the terminal mode.  (2004-12-19)
   http://python.org/sf/1088077  opened by  Mike Meyer

Comments regarding 'macintosh' behaviour wrong for MacOS X  (2004-12-20)
CLOSED http://python.org/sf/1088119  opened by  James Matthew Farrow

zlib decompressobj documentation typo  (2004-12-20)
CLOSED http://python.org/sf/1088206  opened by  Scott David Daniels

calculation wrong rounding  (2004-12-20)
CLOSED http://python.org/sf/1088563  opened by  Sebastian Rockel

_sre.c references uninitialised memory  (2004-12-21)
CLOSED http://python.org/sf/1088891  opened by  Andrew McNamara

need siginterrupt()  on Linux - impossible to do timeouts  (2004-12-21)
   http://python.org/sf/1089358  opened by  Jason

segfault/assert in tokenizer  (2004-12-21)
   http://python.org/sf/1089395  opened by  Walter Dörwald

Carbon.Res misses GetIndString  (2004-12-21)
   http://python.org/sf/1089399  opened by  Jack Jansen

Carbon.File.FSCatalogInfo.createDate implementation  (2004-12-22)
   http://python.org/sf/1089624  opened by  Ronald Oussoren

_DummyThread() objects not freed from threading._active map  (2004-12-22)
   http://python.org/sf/1089632  opened by  saravanand

Carbon.File.FSCatalogInfo.createDate implementation  (2004-12-22)
CLOSED http://python.org/sf/1089643  opened by  Ronald Oussoren

special methods become static  (2004-11-14)
   http://python.org/sf/1066490  reopened by  kquick

mmap missing offset parameter  (2004-12-22)
   http://python.org/sf/1089974  opened by  James Y Knight

exec scoping problem  (2004-12-22)
   http://python.org/sf/1089978  opened by  Kevin Quick

Defaults in ConfigParser.get overrides section values  (2004-12-22)
   http://python.org/sf/1090076  opened by  Gabriel Genellina

presentation typo in lib: 6.21.4.2 How callbacks are called  (2004-12-22)
   http://python.org/sf/1090139  opened by  Jesse Weinstein

Bugs Closed
___

Tests fail instead of skip  (2004-12-11)
   http://python.org/sf/1083645  closed by  bcannon

readline module doesn't build on MacOSX  (2004-12-07)
   http://python.org/sf/1081045  closed by  bcannon

Python 2.4 crashes  (2004-12-12)
   http://python.org/sf/1083793  closed by  axel_kaiser

inspect.py module  (2004-12-18)
   http://python.org/sf/1087551  closed by  jlgijsbers

Possible error during LINKCC check in Configure.in  (2004-06-25)
   http://python.org/sf/980127  closed by  bcannon

example code not working  (2004-12-19)
   http://python.org/sf/1087975  closed by  rhettinger

Shared object modules in Windows have no __file__.  (2003-10-05)
   http://python.org/sf/818315  closed by  loewis

Easier-to-create alternative Python installer for Windows  (2003-08-22)

Re: PHP vs. Python

2004-12-22 Thread Paul Rubin
Jeremy Bowers <[EMAIL PROTECTED]> writes:
> Your point is circular; "fast enough (right now)" can be defined as
> "doesn't need to scale (right now)".
> 
> For any given server app, enough clients will bog it down. If you're
> trying to claim that PHP has less trouble with this, I've seen a lot of
> PHP sites go down under load, so it is clearly not a non-issue.
> 
> Python's scaling isn't automatic, it's just easier to do.

I've never heard of any large sites being done in Python, with or
without scaling.  By a large site I mean one that regularly gets 100
hits/sec or more.  There are many sites like that out there.  Those
are the ones that need to be concerned about scaling.

For sites that get less traffic than that, they only reason they need
to scale if they're written in Python is that Python is too slow.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing new version, erasing previous versions of Python

2004-12-22 Thread Maurice LING
Hi David,
I'm using Python on Mac OSX and although my case is not precisely your 
scenario but it is pretty common to have more than 1 pythons installed 
in Mac OSX 10.3, if Fink is used.

If I understand the above correctly, 1) "make install" and "make altinstall" use
the same process, the only difference being the man page update, and the hard
link, and 2) that previous versions of python are not deleted.  Therefore I
should be able to install 2.4 without deleting 2.2.2.  If I wish to delete
2.3.4, I have to rm -r the appropriate directories.  Any caveats? 
On the assumption that you are using *nix-based system, there shouldn't 
be any problems. But you might want to look at /usr/local/bin/py* files 
and symlinks to get an idea of what you are dealing with.

On MS Windows system, I do not know if there is any registry entries etc 
to be taken care of.

 Is there any
crosstalk between 2.2.2 and 2.4 modules?  Thank you.
Every python seems to maintain its own set of libraries and 3rd party 
packages.

In my case, I've removed Apple-installed python 2.3 by rm -rf the 
appropriate directories and re-symlinked the links in /usr/lib. Fink had 
installed python2.2 and python2.3 in my system and they co-exist 
happily. Each python has its own libraries to use, in my case, in 
/sw/lib/python2.2 and /sw/lib/python2.3

Of course, depending on which python you use to install 3rd party 
libraries, it will go into that python's site-package directory. If any 
causes trouble, I'll guess it will be this.

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


Re: PHP vs. Python

2004-12-22 Thread Jeremy Bowers
On Wed, 22 Dec 2004 16:43:21 -0800, Paul Rubin wrote:

> JZ <[EMAIL PROTECTED]> writes:
>> But pure speed is not the all. Python can scale better,
> 
> If a system is fast enough on a single processor, it doesn't need to scale.

Your point is circular; "fast enough (right now)" can be defined as
"doesn't need to scale (right now)".

For any given server app, enough clients will bog it down. If you're
trying to claim that PHP has less trouble with this, I've seen a lot of
PHP sites go down under load, so it is clearly not a non-issue.

Python's scaling isn't automatic, it's just easier to do.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PHP vs. Python

2004-12-22 Thread Robert Kern
Paul Rubin wrote:
JZ <[EMAIL PROTECTED]> writes:
But pure speed is not the all. Python can scale better,

If a system is fast enough on a single processor, it doesn't need to scale.
I think he means, "scale to larger programs," not "scale to more 
processors."

--
Robert Kern
[EMAIL PROTECTED]
"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter
--
http://mail.python.org/mailman/listinfo/python-list


(Mac-specific) AppScript bug

2004-12-22 Thread George van den Driessche
(This is really for Hamish Sanderson, I think, but I can't find an 
e-mail address for him.)

On OS X 10.3.7, with XCode 1.5 and all the latest AppScript packages 
installed, writing this:

 a = appscript.app( 'XCode.app' )
causes a crash in terminology.py:
/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages/appscript/terminology.py 
in parse(self, path)
   102 osat.parse(path, self)
   103 for code in self._elements.values():
--> 104 name = self._pluralClassNames.get(code, 
self._singularClassNames[code])
   105 self.referencebycode[code] = (kElement, name)
   106 self.referencebyname[name] = (kElement, code)

KeyError: ''
code is a FourCC identifying some part of XCode's script interface. You 
would imagine that every such part would have either a plural name or a 
singular name, but in this case somehow the FourCC '' has ended up 
in self._elements and it has neither. Any idea how that might arise? I 
didn't investigate the origins of the FourCC, which looks like a 
placeholder or error.

If you change the marked line (104) to read:
 			name = self._pluralClassNames.get(code, 
self._singularClassNames.get(code, ''+code))

then the rest of the terminology seems to run fine, and you just end up 
with one bogus entry called '' in the app's attributes.

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


Re: Problem with msvcrt60 vs. msvcr71 vs. strdup/free

2004-12-22 Thread Scott David Daniels
[EMAIL PROTECTED] wrote:
And so I suspect this approach (compiling sources yourself) can shield
people from this ugly mess, if they can build Python 2.4 and the
extensions and have them (core and extension) use one and the same
run-time library. But indeed this might be an issue for those who [1]
use MinGW as their first choice and [2] cannot or won't bother to build
their Python and/or extensions from sources, and hence have to rely on
binary distributions.
I encourage anyone who gets further into solving the "How do I use
MinGW to build Python2.4 (and later) standard-distribution compatible
modules (.pyd s)?" question to share any clues they have.  The MS
free compiler is useful to many, but not all of us.
I expect that MinGW is the most frequent choice for making Python
modules in the "free compiler outside of MS" universe.  Let's make
that one work well, and (once we've done that) we can pass the lessons
on for other compiler is desired.
--Scott David Daniels
[EMAIL PROTECTED]
p.s. I am able (and willing) to use the MS free compiler, but I have
  sympathy for those who aren't.  I'd like to see it possible to use
  _lots_ of different compilers, but we are at the beginning of the
  problem, not the end.  If Intel's compiler is as much faster than
  MS's as it used to be, I may eventually wind up using theirs anyway.
--
http://mail.python.org/mailman/listinfo/python-list


Re: PHP vs. Python

2004-12-22 Thread huy
[EMAIL PROTECTED] wrote:
Anyone know which is faster?  I'm a PHP programmer but considering
getting into Python ... did searches on Google but didn't turn much up
on this.
Thanks!
Stephen
Is PHP too slow for your needs ? Is that the reason for changing ? If it 
is, then Python might not satisfy your need. If it isn't, have you 
thought about why you want to use Python ? If you have, are there 
greater benefits in total over PHP from what you understand of both PHP 
and PYthon.

Not sure where you are currently at with your evaluation of Python so if 
you could outline a few more points on your needs, wants, and 
expectations it would help when answering your questions about Python.

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


Re: Problem with msvcrt60 vs. msvcr71 vs. strdup/free

2004-12-22 Thread abkhd
Martin v. Löwis wrote:
> Indeed, it *will* work most of the time, as you rarely pass resources
> across CRTs in a typical Python extension. However, it is very hard
> to tell from the source code of the extension if such resource
passing
> could ever happen (e.g. what about setlocale(), atexit(), malloc(),
> ...), so if you need something better than "seems to work", you
really
> need to make sure that you understand all the issues, and have a
build
> process that resolves them all.
>
> Regards,
> Martin




You know if I had not tried the example you gave, I'd probably still be
arguing: "but it works." Oh well. Not anymore.

For those who are interested, here is a patch to demo.c of the
\python\dist\src\Demo\embed\demo.c demonstrating what Martin has argued
about above. With such evidence at hand I guess it is safe to say that
the MinGW die-hards will have to improvise. :)

But seriously, and since I don't have the official Python 2.4
distribution yet, and since the pyMinGW compiled Python I use relies on
msvcrt, as opposed to msvcr71, I needed to reverse the roles here to
see the problem first hand: making the "extension" demo use msvcr71 to
see how it reacts with the home-made python24.dll which uses msvcrt.
And sure enough: crash.

Having said that, this seems to me not to be an issue for those who
have or can build Python and/or the extensions they need from sources.
Indeed recompiling the same "demo" to use msvcrt (to use the same
run-time library that my python24.dll uses) instead of msvcr71 yields
the expected correct results without crashes.

And so I suspect this approach (compiling sources yourself) can shield
people from this ugly mess, if they can build Python 2.4 and the
extensions and have them (core and extension) use one and the same
run-time library. But indeed this might be an issue for those who [1]
use MinGW as their first choice and [2] cannot or won't bother to build
their Python and/or extensions from sources, and hence have to rely on
binary distributions.


Regards
Khalid



--- demo.c  Sat Nov 17 08:30:20 2001
+++ demo2.c Thu Dec 23 02:02:40 2004
@@ -34,6 +34,20 @@
/* Note that you can call any public function of the Python
interpreter here, e.g. call_object(). */

+FILE *in;
+int sts;
+
+if ((in = fopen(argv[1], "rt")) == NULL) {
+  fprintf(stderr, "Cannot open program file.\n");
+  return 1;
+}
+
+printf("Working on %s\n", argv[1]);
+sts = PyRun_AnyFile(in, argv[1]) != 0;
+printf("sts: %d\n", sts);
+fclose(in);
+
+
/* Some more application specific code */
printf("\nGoodbye, cruel world\n");

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


Re: Python To Send Emails Via Outlook Express

2004-12-22 Thread ian
Hi Lenard,

As the risk of severely embarassing myself can I ask for your help one
more time.
I have tried changing your script to include attachments, but guess
what, (and this should come as no suprise) I can't do it.
So
Here is my feeble attempt at changing the script..

import os
from ctypes import *

FLAGS = c_ulong
LHANDLE = c_ulong
LPLHANDLE = POINTER(LHANDLE)


# Return codes
SUCCESS_SUCCESS = 0
# Recipient class
MAPI_ORIG = 0
MAPI_TO = 1


NULL = c_void_p(None)


class MapiRecipDesc(Structure):
_fields_ = [('ulReserved', c_ulong),
('ulRecipClass', c_ulong),
('lpszName', c_char_p),
('lpszAddress', c_char_p),
('ulEIDSize', c_ulong),
('lpEntryID', c_void_p),
]
lpMapiRecipDesc = POINTER(MapiRecipDesc)


class MapiFileDesc(Structure):
_fields_ = [('ulReserved', c_ulong),
('flFlags', c_ulong),
('nPosition', c_ulong),
('lpszPathName', c_char_p),
('lpszFileName', c_char_p),
('lpFileType', c_void_p),
]
lpMapiFileDesc = POINTER(MapiFileDesc)


class MapiMessage(Structure):
_fields_ = [('ulReserved', c_ulong),
('lpszSubject', c_char_p),
('lpszNoteText', c_char_p),
('lpszMessageType', c_char_p),
('lpszDateReceived', c_char_p),
('lpszConversationID', c_char_p),
('flFlags', FLAGS),
('lpOriginator', lpMapiRecipDesc), # ignored?
('nRecipCount', c_ulong),
('lpRecips', lpMapiRecipDesc),
('nFileCount', c_ulong),
('lpFiles', lpMapiFileDesc),
]
lpMapiMessage = POINTER(MapiMessage)


MAPI = windll.mapi32


MAPISendMail=MAPI.MAPISendMail
MAPISendMail.restype = c_ulong  # Error code
MAPISendMail.argtypes = (LHANDLE,   # lhSession
c_ulong,   # ulUIParam
lpMapiMessage, # lpMessage
FLAGS, # lpFlags
c_ulong,   # ulReserved
)


def SendMail(recipient, subject, body, attach=[]):
"""Post an e-mail message using Simple MAPI


recipient - string: address to send to
subject - string: subject header
body - string: message text
attach - string: files to attach
"""
attach = map( os.path.abspath, attach )
nFileCount = len(attach)
if attach:
MapiFileDesc_A = MapiFileDesc * len(attach)
fda = MapiFileDesc_A()
for fd, fa in zip(fda, attach):
fd.ulReserved = 0
fd.flFlags = 0
fd.nPosition = -1
fd.lpszPathName = fa
fd.lpszFileName = None
fd.lpFileType = None
lpFiles = fda


recip = MapiRecipDesc(0, MAPI_TO, None, recipient, 0, None)
#msg = MapiMessage(0, subject, body, None, None, None, 0,
# cast(NULL, lpMapiRecipDesc), 1, pointer(recip),
# nFileCount, cast(NULL, lpMapiFileDesc))
msg = MapiMessage(0, subject, body, None, None, None, 0,
cast(NULL, lpMapiRecipDesc), 1, pointer(recip),
nFileCount, cast(NULL, lpFiles))


rc = MAPISendMail(0, 0, byref(msg), 0, 0)
if rc != SUCCESS_SUCCESS:
raise WindowsError, "MAPI error %i" % rc

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


Re: wxPython help

2004-12-22 Thread Scott David Daniels
km wrote:
Hi all,
i am trying out some of the demo programs in wxPython.
but i am getting an error:
no module 'run'
how do i circumvent this module and run the program with main.Loop() ?
tia,
KM 
The easiest way is to copy
"C:\Program Files\wxPython2.5 Docs and Demos\demo\run.py"
(run.py from the same directory where demo.py or demo.pyw lives)
to your local directory where you are playing.
--Scott David [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression: perl ==> python

2004-12-22 Thread Stephen Thorne
On 22 Dec 2004 17:30:04 GMT, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
> Is there an easy way round this?  AFAIK you can't assign a variable in
> a compound statement, so you can't use elif at all here and hence the
> problem?
> 
> I suppose you could use a monstrosity like this, which relies on the
> fact that list.append() returns None...
> 
> line = "123123"
> m = []
> if m.append(re.search(r'^(\d+)$', line)) or m[-1]:
>print "int",int(m[-1].group(1))
> elif m.append(re.search(r'^(\d*\.\d*)$', line)) or m[-1]:
>print "float",float(m[-1].group(1))
> else:
>print "unknown thing", line

I wrote a scanner for a recursive decent parser a while back. This is
the pattern i used for using mulitple regexps, instead of using an
if/elif/else chain.

import re
patterns = [
(re.compile('^(\d+)$'),int),
(re.compile('^(\d+\.\d*)$'),float),
]

def convert(s):
for regexp, action in patterns:
m = regexp.match(s)
if not m:
continue
return action(m.group(1))
raise ValueError, "Invalid input %r, was not a numeric string" % (s,)

if __name__ == '__main__':
tests = [ ("123123",123123), ("123.123",123.123), ("123.",123.) ]
for input, expected in tests:
assert convert(input) == expected

try:
convert('')
convert('abc')
except:
pass
else:
assert None,"Should Raise on invalid input"


Of course, I wrote the tests first. I used your regexp's but I was
confused as to why you were always using .group(1), but decided to
leave it. I would probably actually send the entire match object to
the action. Using something like:
(re.compile('^(\d+)$'),lambda m:int(m.group(1)),
and
return action(m)

but lambdas are going out fashion. :(

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


Re: PHP vs. Python

2004-12-22 Thread Paul Rubin
JZ <[EMAIL PROTECTED]> writes:
> But pure speed is not the all. Python can scale better,

If a system is fast enough on a single processor, it doesn't need to scale.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PHP vs. Python

2004-12-22 Thread JZ
Dnia 22 Dec 2004 14:03:36 -0800, [EMAIL PROTECTED] napisał(a):

> Anyone know which is faster?  I'm a PHP programmer but considering
> getting into Python ... 

Python application servers (Webware, Skunkweb) can work much faster than
php. But it is true only for non-trivial code. Benchmark for "Hello world"
is a nonsense of course. 

But pure speed is not the all. Python can scale better, has cleaner and
consistent syntax, better standard libraries and is a common language
rather than specific script language for web only.

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


Re: Is this a good use for lambda

2004-12-22 Thread Terry Reedy

"Nick Coghlan" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Although if you genuinely prefer a functional programming style,
> I'd go with  Terry's answer rather than mine.

The 'iterative' version can also be written recursively, which to most is 
functional.  For me, the important question for general composition is 
whether one unpacks the sequence of functions to construct a nested 
sequence of wrappers (via compose2) *before* one has any data to apply it 
to, or whether one bundles the flat list of functions, as it is, with a 
generic composer which, once it gets a piece of data to operate on, unpacks 
and applies the functions one at a time.  The former has a certain 
theoretical elegance, the latter seems more practical and, for Python, 
probably faster.  So my previous answer was about how the make the former 
approach perhaps clearer, by explicit naming compose2, but not a claim that 
it is necessarily the 'better' approach.

> (Incidentally, I didn't even know what the reduce trap *was* until Terry 
> described it, but the iterative version avoids it automatically)

Yes, I noticed that   A properly-written recursive version of the unpack 
and apply algorithm would do the same.

To me, Python's builtin reduce has two related problems.  The second is 
that it overlays two related but distinct functions, one with three 
parameters and the other, a special case, with just two.  The first problem 
is that as one way to do the second, it defines the three parameter 
function with contradictory parameter orders.

To explain the first:  the three-param signature of Python's reduce is
reduce(update_result_with_item, items, initial_result)
The order of result and item(s) is switched between the update function and 
reduce itself.  Some people (including GvR according to a post on PyDev) 
find this confusing and error-prone enough that they avoid using reduce.

The proper, order-consistent signature is either
reduce(update_result_with_item, initial_result, items)
or possibly (but I prefer the above)
reduce(apply_item_toupdate_result, items, initial_result)
so that the order of the args to the update function matchwa the order they 
are given to reduce.

As to the second problem: if the abbreviated and slightly specialized
reduce1(updater, items), equivalent to
def reduce1(updater, items):
if items: return reduce(updater, items[0], items[1:])
else raise TypeError("reduce1 requires at least 1 item")
is important enough to be in builtins, then perhaps it was/is important 
enough to have its own name instead of being overlayed on reduce with a 
perverted signature.  (Though, reduce1(applier, items) *could* be overlayed 
on full reduce with the second consistent signature).

Terry J. Reedy



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


Re: PHP vs. Python

2004-12-22 Thread Russell E. Owen
In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] wrote:

>Anyone know which is faster?  I'm a PHP programmer but considering
>getting into Python ... did searches on Google but didn't turn much up
>on this.

For web service, the first hurdle is picking which python web interface 
to use, installing it and (if necessary) configuring your web server to 
use it. (All that choice is great in many respects, but it does 
complicate getting started.)

Anyway, once you've done that, i doubt you'll find any speed issues with 
python, and it is a more pleasant language than PHP. (Unfortunately, 
that initial hurdle can be a big one; I am still using PHP on my server 
because I never cleared it.)

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


Re: PHP vs. Python

2004-12-22 Thread Stephen Thorne
On 22 Dec 2004 14:03:36 -0800, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> Anyone know which is faster?  I'm a PHP programmer but considering
> getting into Python ... did searches on Google but didn't turn much up
> on this.

In terms of development, Python is a far better language to write code
in[1], has a much more mature standard library[2]  and an excellent
community[3].

I've avoided your original question. Speed. Python is faster to
develop in, and is on-par with execution time. The trick is, with
python, you can trivially profile your application and re-write any
sections of code that are too slow in C, in pyrex, optimise them with
psyco, or just plain fix your efficiency problems.

Profiling in php isn't as easy as
import profile
profile.run("main()")

Regards,
Stephen Thorne.

[1] I have written php commerically for over 3 years. This isn't a
subjective look-from-afar. I actually know from down and dirty day-in
day-out experience.
[2] compare http://pear.php.net to "apt-cache search ^python"
[3] Look at http://bugs.php.net/ . There's something fundamentally
wrong with a language community where people who have stumbled on
honest-to-god bugs are abused.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Metaclasses

2004-12-22 Thread Shalabh Chaturvedi
[EMAIL PROTECTED] wrote:
I am trying to build a capability based API. That is, an instance of the
api will reflect the capabilities of some underlying services. 
The question I'd ask at this point is - does the term 'instance of the 
API' correspond to a Python class, or an instance of the class that you 
define? In case you want to have one class per API, you'd have multiple 
classes in which case metaclasses *may* be useful (but still not 
required). In case you want to have one instance per API such that each 
instance has a different set of methods,  you don't need metaclasses at all.

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


Re: Best GUI for small-scale accounting app?

2004-12-22 Thread huy
Dave Cook wrote:
On 2004-12-20, Paul Rubin  wrote:

I think I can put together a useable (but not visually stunning) web
interface faster than I can put together any pure client-side
interface.  

Web browser "widgets" seem pretty limited to me, though.  You don't even
have something as simple as a combo box (i.e. an editable entry with a drop
down), let alone the rich set of widgets something like wxwidgets offers.
Also web development doesn't seem as coherent to me as development with a
good GUI framework.
I think it depends on your target audience. Many people love simplicity. 
 Many people hate multiple tabs, tree structures, deep nested menus etc 
etc. If you wanted to make a web program as complex as a rich client 
program then it's probably a bad idea to do as a web program. But If you 
wanted to keep it simple, then I'd go with a web program any day.

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


Re: PHP vs. Python

2004-12-22 Thread Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.
Hi !

Relative in Python (and for local use), PHP is a tortoise with of a hand
brake.



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


Re: word to digit module

2004-12-22 Thread John Machin

Stephen Thorne wrote:
> Thankyou for you feedback, both of you.

No wuckas.

> http://thorne.id.au/users/stephen/scripts/eng2num.py contains your
suggestions.

This points to some javascript which prints "No."

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


Re: Newbie question - default values of a function

2004-12-22 Thread Bulba!

Thanks everyone (esp. Fredrik, http://www.effbot.org/zone/index.htm
contains lotsa goodies by him I intend to study), I'm going offline to
reboot my  brain. ;-) 



--
It's a man's life in a Python Programming Association.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression: perl ==> python

2004-12-22 Thread John Machin

Fredrik Lundh wrote:
> John Machin wrote:
>  >
> >> > I forgot to add: I am using Python 2.3.4/Win32 (from
ActiveState.com). The
> >> > code works in my interpreter.
> >>
> >> only if you type it into the interactive prompt.  see:
> >
> > No, it doesn't work at all, anywhere. Did you actually try this?
>
> the OP claims that it works in his ActiveState install (PythonWin?).
maybe he
> played with re.search before typing in the commands he quoted; maybe
Python-
> Win contains some extra hacks?
>
> as I've illustrated earlier, it definitely doesn't work in a script
executed by a standard
> Python...
>
> 

It is quite possible that the OP played with re.search before before
typing in the commands he quoted; however *you* claimed that it [his
quoted commands] worked "only if you type it into the interactive
prompt". It doesn't work, in the unqualified sense that I understood.

Anyway, enough of punch-ups about how many dunces can angle on the hat
of a pun -- I did appreciate your other posting about multiple patterns
and "lastindex"; thanks.

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


Re: list IndexError

2004-12-22 Thread Mike C. Fletcher
Ishwor wrote:
...
I believe lamda's are unnamed functions aren't they?? Still learning... ;-)
 

Yes.
yeah actually i saw what Fedrik had to say above. I created a sliced
copy of the l & did my homework within the for loop
 

You might want to check it again before you hand it in ;) ...
>>> def ishwor( source ):
... for item in source:
... if item == 'd':
... source.remove( item )
...
>>> d = ['a','b','c','d','e']
>>> ishwor( d )
>>> d
['a', 'b', 'c', 'e']

Well, that worked fine, but wait a minute...
>>> d = ['a','b','c','d','d','e']
>>> ishwor( d )
>>> d
['a', 'b', 'c', 'd', 'e']
This is the same problem as you saw before.  Under the covers, the 
Python interpreter is written such that it's keeping track of the index 
into the list as an integer.  When you mutate the list, that integer 
gets out-of-sync with the value you think you're processing.

The while form I provided avoids that by re-scanning the *whole* list 
every time it does the check.  The filtering forms do it by working on a 
temporary list.  The reverse-index form does it by only deleting from 
the segment of the list *after* the point where the to-be-done indices 
reference.

This code is so clean and looks very healthy. :) Python will live a
long way because its a cute language. :-)
 

Cute is, of course, the highest praise to which any man, woman or 
language can aspire :) .

  for index in xrange( len(source)-1, -1, -1 ):
 if source[i] == 'e':
del source[i]
   

thanx Mike, i have tried this C-ish way as well . :-) it seemed quiete
ok for my  small list but dont know about huge lists.
 

It's actually *good* for huge lists where you only want to delete a few 
items, that's it's main attraction, it doesn't copy the list at all 
(though each deletion causes a memcopy of all pointers from that element 
in the list onward, that's a fairly faster operation).  It's going to 
avoid new memory allocation much of the time, and doesn't have the "scan 
the whole list for each deletion" overhead of the "while x in list" version.

Anyway, have fun,
Mike

 Mike C. Fletcher
 Designer, VR Plumber, Coder
 http://www.vrplumber.com
 http://blog.vrplumber.com
--
http://mail.python.org/mailman/listinfo/python-list


Problem with os.listdir and delay with unreachable network drives on Windows

2004-12-22 Thread Read Roberts
I wrote my own directory browser in order to get around a bug where 
tkFileDialog.askdirectory()  can't handle non-ascii paths. However, I 
have a problem where I call os.listdir() on a  mapped network drive, 
e.g. os.listdir("Z:\\"), and if the network drive is unavailable, the 
UI hangs  until the OS returns with an exception because the network 
shared drive is unavailable.

 I would like to work around this by simply not looking into  mapped 
drives that are not currently mounted.  Is there some way to check 
the status of mapped drive to see if it is currently mounted, or a 
better solution? ( I use the call win32api.GetLogicalDriveStrings() 
to get the list of available drives).

Also, is there any way to enumerate remote volumes that are mounted 
by not mapped? I can't easily find this in the win32 stuff or via 
googling. The win32net calls to enumerate servers and shares sound 
likely, but don't show such volumes on my system, although I may not 
be using the right arguments.

I have the current Windows binary install of Python 2.3.4 on my 
Windows XP system.

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


Re: Skinnable/Stylable windows in wxPython?

2004-12-22 Thread Roel Schroeven
Daniel Bickett wrote:
Not only would this make it more multi-platform (I have no access to
a GTK machine so I don't know if this works. Could someone please
check?)
Looks like it works (I had to change frame.Show() to frame.Show(1)
though, but that could be because it's an old version).

No, I think that was a slip on my part when copying the code from one
screen to the next :)
I tried again with newer versions (Python 2.3 and wxPython 2.4); the 
code runs as-is, without that modification.

One odd thing
though: the Windows version doesn't react to clicking or dragging the
mouse, which seems to be the expected behavior.

The GTK version can be
moved by dragging the mouse; even just clicking the mouse moves the
window somewhat down and to the left.

That's interesting... I wonder if using those methods would conflict
at all.
I couldn't reproduce that behaviour this time. It might have had 
something to do with the test setup the first time.

--
"Codito ergo sum"
Roel Schroeven
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python for Series 60 update

2004-12-22 Thread Tim Hoffman
Whoo hoo.
Just got it.
I did find a problem with it on my 7610.
It has a python program called bt_console.py which
allows you to start a ptyhon shell, but its I/O is
redirected over Bluetooth to a terminal on a PC (ie Hyper Term)
It goves you have access to the Python shell with a decent
keyboard and screen size through the terminal.
It works, but I had to hard code my bluetooth mac address (I assume
thats what it is called in bluetooth).  The bt_discover() call
didn't seem to find my host.
It doesn't include xmlrpclib in the base installed python runtime,
but just send xmlrpclib, and xmlib and away we go.
from the console I could immediatly do xml-rpc calls
to my favourite Zope/CMF instance over GPRS and it just worked.
This is cool.
Tim
Ville Vainio wrote:
Python for S60 seems to be available for the grand public as of today.
Check out
http://www.forum.nokia.com/main/0,,034-821,00.html
Yes, this is good news :-).
--
http://mail.python.org/mailman/listinfo/python-list


Re: extract news article from web

2004-12-22 Thread Zhang Le
Thanks for the hint. The xml-rpc service is great, but I want some
general techniques to parse news information in the usual html pages.

Currently I'm looking at a script-based approach found at:
http://www.namo.com/products/handstory/manual/hsceditor/
User can write some simple template to extract certain fields from a
web page. Unfortunately, it is not open source, so I can not look
inside the blackbox.:-(

Zhang Le

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


Re: Newbie question - default values of a function

2004-12-22 Thread Fredrik Lundh
"Bulba!" wrote:

> Surely the variable i is a mutable object?

nope.

> OK, again:
>
 def t(a,i=[0]):
> ... i[0]=i[0]+1
> ... return (a, i)
> ...
 t(1)
> (1, [1])
 t(3)
> (3, [2])
 t(5)
> (5, [3])
>
> Yes, it works with the list. But why sharing value between calls
> pertains some mutable objects and not the other mutable objects?

a variable is not an object.

reset your brain, and read this:

http://www.effbot.org/zone/python-objects.htm

or the longer version:

http://starship.python.net/crew/mwh/hacks/objectthink.html

 



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


Re: Help to find a library...

2004-12-22 Thread Fredrik Lundh
"whamoo" wrote

>> > I'm looking for a library like ncurses, but that can be used also on
>> > windows in a very simple way...
>> >
>> > There is some library that do some like curses?
>>
>> here's one:
>>
>> http://www.effbot.org/zone/console-index.htm
>
> Thanks for this library, but i was looking for a cross-platform library,
> i need it for linux, macosx, and also windows

sorry, missed the "also".  googling for "python curses windows" (without the
quotes) brings up a couple of hits, including:

http://flangy.com/dev/python/curses/

might or might not work with the latest python.

on the other hand, you could restrict yourself to using only a subset of curses,
and write some glue code to map the functions in that subset to console calls.
creating custom abstraction layers in Python is embarassingly easy...

 



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


Re: Newbie question - default values of a function

2004-12-22 Thread Bulba!
On Wed, 22 Dec 2004 22:29:44 GMT, "Matt Gerrans" <[EMAIL PROTECTED]>
wrote:

>Actually i was not mutable.   Try this:

>i = 1
>id(i)
>i += 1
>id(i)

Looks like I will have to read the Language Reference anyway. :-(


>Because you are assigning the local reference variable L to a new list, 
>instead of modifying that original default list that was created.

>Is that more clear, or is it now more unclear?   ;) 

Clear now, but I have to say for someone who's been doing
some C programming in the past it is pretty confusing, because 
I'm used to think of any variable as basically a place in memory
with a pointer to it, so anything without #define or const was
considered "mutable" (gawd I still hate pointers).

C-style thinking considered harmful when programming in Python. :o)




--
It's a man's life in a Python Programming Association.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list IndexError

2004-12-22 Thread M.E.Farmer
Hello Ishwor ,
The simpliest way I can explain slicing is that the slices point to the
spot *between* the items..
Take this list for example
slicer =  [0,1,2,3,4,5]
>>> slicer [1]
1
>>> slicer [1:2]
[1]
>>> slicer [:-1]
 [0,1,2,3,4] 
>>> slicer[2,4]
[2,3]

Hth,
 M.E.Farmer

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


Re: Help to find a library...

2004-12-22 Thread whamoo
Fredrik Lundh <[EMAIL PROTECTED]> wrote:

> "whamoo" <[EMAIL PROTECTED]> wrote:
> 
> > I'm looking for a library like ncurses, but that can be used also on
> > windows in a very simple way...
> >
> > There is some library that do some like curses?
> 
> here's one:
> 
> http://www.effbot.org/zone/console-index.htm

Thanks for this library, but i was looking for a cross-platform library,
i need it for linux, macosx, and also windows

I'm going to write a rouge-like game (nethack, adom, moria), but curses
only work on unix platform...

-- 
Whamoo www.rknet.it
Powerd by: MacOsX, Gnu/Linux Debian Sarge,
Amiga Os 3.9, Milk.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PHP vs. Python

2004-12-22 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> Anyone know which is faster?  I'm a PHP programmer but considering
> getting into Python ...

faster for what?  in my experience, people can hack into a PHP site in
no time at all, but maybe you meant something else?

(seriously, it depends on what you're doing, of course.  and how you're
running your programs.  and what kind of programs you're writing.  and
what frameworks you're using.  and, and. and, ...)

 



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


Re: Newbie question - default values of a function

2004-12-22 Thread Matt Gerrans
Actually i was not mutable.   Try this:

i = 1
id(i)
i += 1
id(i)

Change both of your sample functions to also print the id of the default 
variable and that might shed a little more light on the matter.

"i = i + 1" is only changing the local reference called i to refer to an 
instance of a different integer object.If you change the original 
function to something similar, it will behave similarly:

def f( a, L=[]):
   L = L + [a]
   return L

Because you are assigning the local reference variable L to a new list, 
instead of modifying that original default list that was created.

Is that more clear, or is it now more unclear?   ;) 


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


Re: PHP vs. Python

2004-12-22 Thread Marek Baczynski
That depends what you consider faster. PHP will save you some q&d
hacking time, but Python will save you more in the longer term IMHO.
For the other speed, see http://shootout.alioth.debian.org/

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


Re: Newbie question - default values of a function

2004-12-22 Thread Dennis Benzinger
Bulba! wrote:
> [...]
> But why the following happens?
> 
> 
def j(a,i=0):
> 
> ...   i=i+1 
> ...   return (a, i)
> ... 
> 
j(2)
> 
> (2, 1)
> 
j(3)
> 
> (3, 1)
> 
j(5)
> 
> (5, 1)
> 
> 
> From Language Reference:
> 
> http://www.python.org/doc/2.3.4/ref/function.html
> 
> "Default parameter values are evaluated when the function definition
> is executed. This means that the expression is evaluated once, when
> the function is defined, and that that same ``pre-computed'' value is
> used for each call. This is especially important to understand when a
> default parameter is a mutable object, such as a list or a dictionary:
> if the function modifies the object (e.g. by appending an item to a
> list), the default value is in effect modified. "
> 
> 
> Surely the variable i is a mutable object?
> [...]

No, i is not mutable!
i is a name for a number object which is _not_ mutable
(http://www.python.org/doc/2.4/ref/types.html).

The line i=i+1 creates a new number object with the value 1 and gives it
the name i.


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


Re: A rational proposal

2004-12-22 Thread Mike Meyer
Nick Coghlan <[EMAIL PROTECTED]> writes:

> Actually, I was misremembering how Decimal worked - it follows the rule you 
> suggest:
>
> float() + Decimal() fails with a TypeError
> float() + float(Decimal()) works fine
>
> And I believe Decimal's __float__ operation is a 'best effort' kind of
> thing, so I have no problem with Rationals working the same way.

Actually, I suggested that:

float() + Rational() returns float

You're suggesting that the implicit conversion to float not happen
here, and the user be forced to cast it to float? And you're saying
Decimal does it that way.[

That's good enough for me.

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help to find a library...

2004-12-22 Thread Fredrik Lundh
"whamoo" <[EMAIL PROTECTED]> wrote:

> I'm looking for a library like ncurses, but that can be used also on
> windows in a very simple way...
>
> There is some library that do some like curses?

here's one:

http://www.effbot.org/zone/console-index.htm

 



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


Re: list IndexError

2004-12-22 Thread Ishwor
On Wed, 22 Dec 2004 21:42:16 GMT, Steven Bethard
<[EMAIL PROTECTED]> wrote:
> Ishwor wrote:
> > i am trying to remove an item 'e' from the list l
> 
> I thought it might be helpful to code some of the alternatives you've
> been given and look at the timings to put things into perspective.  The
> code:
> 
>  remove.py 
> def remove_lc(x, lst):
> lst[:] = [item for item in lst if item != x]
> 
> def remove_list(x, lst):
> result = []
> for item in lst:
> if item != x:
> result.append(item)
> lst[:] = result
> 
> def remove_filter(x, lst):
> lst[:] = filter(lambda item: item != x, lst)
> 
> def remove_xrange(x, lst):
> for i in xrange(len(lst)-1, -1, -1):
> if lst[i] == x:
> del lst[i]
> 
> def remove_remove(x, lst):
> while x in lst:
> lst.remove(x)
> 
> def remove_try(x, lst):
> try:
> while True:
> lst.remove(x)
> except ValueError:
> pass
> 
> def remove_ishwor(x, lst):
> for item in lst[:]:
> if item == x:
> lst.remove(x);
> --
> 
> First, some timings when only 1 out of every 1000 elements needs to be
> removed.  Timings were taken with Python 2.4 on a 2.26 Ghz Windows box
> using:
> $ python -m timeit -s "import remove; lst = [x % 1000 for x in
> xrange(1)]" "remove.remove_(500, lst)"
> 
> remove_remove:  516 usec per loop
> remove_try: 604 usec per loop
> remove_ishwor: 1.61 msec per loop
> remove_xrange: 2.29 msec per loop
> remove_lc: 2.37 msec per loop
> remove_list:   5.3  msec per loop
> remove_filter: 5.65 msec per loop
> 
> Now, some timings when 1 out of every 10 elements needs to be removed.
> Timings were taken using:
> $ python -m timeit -s "import remove; lst = [x % 10 for x in
> xrange(1)]" "remove.remove_(5, lst)"
> 
> remove_lc:  2.03 msec per loop
> remove_xrange:  2.08 msec per loop
> remove_list:4.72 msec per loop
> remove_filter:  5.17 msec per loop
> remove_try:30.7  msec per loop
> remove_ishwor: 31.5  msec per loop
> remove_remove: 60.2  msec per loop
> 
> The moral of the story here is that, if the items to be removed only
> make up a very small percentage of the list, an approach like
> remove_remove or remove_try might be okay.  On the other hand, if you
> expect the items to be removed will make up even a moderate percentage
> of the list (e.g. 10%), then remove_lc or remove_xrange is a vastly
> better alternative.
> 
> Steve
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
umm... looks good.. i am running these task sets on my box as well
slightly slower than yours 2.4Ghz... thanx Steve. :-) now i'll sit
back and dwell a bit deeper into it now.


-- 
cheers,
Ishwor Gurung
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tabnanny really useful?

2004-12-22 Thread JanC
Steve Holden schreef:

> Sounds like WingIDE to me. I'm a recent convert, but one feature that 
> impressed me was the instant warning I got when I indented code with 
> spaces in a tab-oriented source file.

>From the SciTE/Scintilla docs:

| tab.timmy.whinge.level
| 
| For Python code, checks whether indenting is consistent. The default, 0 
| turns off indentation checking, 1 checks whether each line is 
| potentially inconsistent with the previous line, 2 checks whether any 
| space characters occur before a tab character in the indentation, 3 
| checks whether any spaces are in the indentation, and 4 checks for any 
| tab characters in the indentation.
| 1 is a good level to use.

It's also in de wxSTC docs:

(Below the lexers table.)


-- 
JanC

"Be strict when sending and tolerant when receiving."
RFC 1958 - Architectural Principles of the Internet - section 3.9
-- 
http://mail.python.org/mailman/listinfo/python-list


Newbie question - default values of a function

2004-12-22 Thread Bulba!

OK. Don't laugh.


There's this example from tutorial, showing how default
value is computed once when defining function and shared 
between function calls:

---
def f(a, L=[]):
L.append(a)
return L

print f(1)
print f(2)
print f(3)

This will print

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

(PythonWin 2.3.4 (#53, Oct 18 2004, 20:35:07) [MSC v.1200 32 bit
(Intel)] on win32.)


Tried it, it works as expected.

But why the following happens?

>>> def j(a,i=0):
... i=i+1 
... return (a, i)
... 
>>> 
>>> j(2)
(2, 1)
>>> j(3)
(3, 1)
>>> j(5)
(5, 1)


>From Language Reference:

http://www.python.org/doc/2.3.4/ref/function.html

"Default parameter values are evaluated when the function definition
is executed. This means that the expression is evaluated once, when
the function is defined, and that that same ``pre-computed'' value is
used for each call. This is especially important to understand when a
default parameter is a mutable object, such as a list or a dictionary:
if the function modifies the object (e.g. by appending an item to a
list), the default value is in effect modified. "


Surely the variable i is a mutable object?

OK, again:

>>> def t(a,i=[0]):
... i[0]=i[0]+1
... return (a, i)
... 
>>> t(1)
(1, [1])
>>> t(3)
(3, [2])
>>> t(5)
(5, [3])

Yes, it works with the list. But why sharing value between calls
pertains some mutable objects and not the other mutable objects? 
I'm stymied.



--
It's a man's life in a Python Programming Association.
-- 
http://mail.python.org/mailman/listinfo/python-list


PHP vs. Python

2004-12-22 Thread stephen . mayer
Anyone know which is faster?  I'm a PHP programmer but considering
getting into Python ... did searches on Google but didn't turn much up
on this.

Thanks!
Stephen

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


Re: Why no list heritable type?

2004-12-22 Thread Dave Benjamin
Mike Meyer wrote:
"Robert Brewer" <[EMAIL PROTECTED]> writes:
Why aren't built 
in lists and dictionaries real heritable types that can save 
this kind of patchwork?
They are since Python 2.2 (IIRC):
And before Python 2.2 there was the UserList class in the standard
library. Which is still there in 2.4. Shouldn't it be depreciated by
this point?
Please keep in mind that the latest stable version of Jython is 2.1, 
which does not support subclassing "list", and "dict" does not exist at all:

Jython 2.1 on java1.4.2_01 (JIT: null)
Type "copyright", "credits" or "license" for more information.
.>>> class C(list): pass
...
Traceback (innermost last):
  File "", line 1, in ?
TypeError: base is not a class object: instance of 
'org.python.core.BuiltinFunctions'
.>>> class D(dict): pass
...
Traceback (innermost last):
  File "", line 1, in ?
NameError: dict

I'm sure there are workarounds that will make the above code work in 
both CPython and Jython, but until there is a stable release of Jython 
that natively supports subclassing "list" and "dict", I'd appreciate it 
if we didn't deprecate (or depreciate =) UserList/Dict just yet. I 
maintain several modules that are portable to both implementations.

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


Re: regular expression: perl ==> python

2004-12-22 Thread Fredrik Lundh
John Machin wrote:
 >
>> > I forgot to add: I am using Python 2.3.4/Win32 (from ActiveState.com). The
>> > code works in my interpreter.
>>
>> only if you type it into the interactive prompt.  see:
>
> No, it doesn't work at all, anywhere. Did you actually try this?

the OP claims that it works in his ActiveState install (PythonWin?).  maybe he
played with re.search before typing in the commands he quoted; maybe Python-
Win contains some extra hacks?

as I've illustrated earlier, it definitely doesn't work in a script executed by 
a standard
Python...

 



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


Re: [Re: newbie question]

2004-12-22 Thread Doug Holton
Ed Leafe wrote:
You've missed the obvious: it's 'criticism' or 'observation' when it 
comes from Doug, but it's a 'flame' when it is directed at Doug.
>
Unless there is something more substantial then whining, howzabout 
we all just ignore it and let it die a quick death?
It's amazing how many of you guys try this - spew some filth and then 
beg people to stop the thread right now.

Speaking of Ed Leafe:
"You might want to check out Dabo, an application framework of which 
I am one of the authors."

What are you selling?
"We offer one-on-one live phone, chat, or on-site support at an hourly 
rate, with a minimum charge of one hour plus phone charges or travel 
costs. Contact the authors (Ed Leafe and Paul McNett) for more information."
--
http://mail.python.org/mailman/listinfo/python-list


Re: list IndexError

2004-12-22 Thread Steven Bethard
Ishwor wrote:
i am trying to remove an item 'e' from the list l
I thought it might be helpful to code some of the alternatives you've 
been given and look at the timings to put things into perspective.  The 
code:

 remove.py 
def remove_lc(x, lst):
lst[:] = [item for item in lst if item != x]
def remove_list(x, lst):
result = []
for item in lst:
if item != x:
result.append(item)
lst[:] = result
def remove_filter(x, lst):
lst[:] = filter(lambda item: item != x, lst)
def remove_xrange(x, lst):
for i in xrange(len(lst)-1, -1, -1):
if lst[i] == x:
del lst[i]
def remove_remove(x, lst):
while x in lst:
lst.remove(x)
def remove_try(x, lst):
try:
while True:
lst.remove(x)
except ValueError:
pass
def remove_ishwor(x, lst):
for item in lst[:]:
if item == x:
lst.remove(x);
--
First, some timings when only 1 out of every 1000 elements needs to be 
removed.  Timings were taken with Python 2.4 on a 2.26 Ghz Windows box 
using:
$ python -m timeit -s "import remove; lst = [x % 1000 for x in 
xrange(1)]" "remove.remove_(500, lst)"

remove_remove:  516 usec per loop
remove_try: 604 usec per loop
remove_ishwor: 1.61 msec per loop
remove_xrange: 2.29 msec per loop
remove_lc: 2.37 msec per loop
remove_list:   5.3  msec per loop
remove_filter: 5.65 msec per loop
Now, some timings when 1 out of every 10 elements needs to be removed. 
Timings were taken using:
$ python -m timeit -s "import remove; lst = [x % 10 for x in 
xrange(1)]" "remove.remove_(5, lst)"

remove_lc:  2.03 msec per loop
remove_xrange:  2.08 msec per loop
remove_list:4.72 msec per loop
remove_filter:  5.17 msec per loop
remove_try:30.7  msec per loop
remove_ishwor: 31.5  msec per loop
remove_remove: 60.2  msec per loop

The moral of the story here is that, if the items to be removed only 
make up a very small percentage of the list, an approach like 
remove_remove or remove_try might be okay.  On the other hand, if you 
expect the items to be removed will make up even a moderate percentage 
of the list (e.g. 10%), then remove_lc or remove_xrange is a vastly 
better alternative.

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


Re: word to digit module

2004-12-22 Thread Stephen Thorne
On Wed, 22 Dec 2004 11:41:26 -0800, Scott David Daniels
<[EMAIL PROTECTED]> wrote:
> John Machin wrote:
> > Stephen Thorne wrote:
> > .def toNumber2(s):
> > .   items = s.replace(',', '').split()
> > .   numbers = [translation.get(item.strip(), -1) for item in items if
> > item.strip()]
> > .   stack = [0]
> > .   for num in numbers:
> > .  if num == -1:
> > . raise ValueError("Invalid string '%s'" % (s,))
> > .  if num >= 100:
> > . stack[-1] *= num
> > . if num >= 1000:
> > .stack.append(0)
> > .  else:
> > . stack[-1] += num
> > .   return sum(stack)
> >
> 
> Can I play too?
> Let's replace the top with some little bit of error handling:
> 
>  def toNumber3(text):
>  s = text.replace(',', '').replace('-', '')# for twenty-three
>  items = s.split()
>  try:
>  numbers = [translation[item] for item in items]
>  except KeyError, e:
>  raise ValueError, "Invalid element %r in string %r" % (
> e.args[0], text)
>  stack = [0]
>  for num in numbers:
>  if num >= 100:
>  stack[-1] *= num
>  if num >= 1000:
>  stack.append(0)
>  else:
>  stack[-1] += num
>  return sum(stack)

Thankyou for you feedback, both of you.
http://thorne.id.au/users/stephen/scripts/eng2num.py contains your suggestions.

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


Re: list IndexError

2004-12-22 Thread Ishwor
On Thu, 23 Dec 2004 07:27:52 +1000, Egor Bolonev <[EMAIL PROTECTED]> wrote:
> On Thu, 23 Dec 2004 06:56:02 +1030, Ishwor <[EMAIL PROTECTED]> wrote:
> 
>  l
> > ['a', 'b', 'c', 'd', 'e']
>  for x in l[:]:
> >if x == 'd':
> >l.remove('d');
> >
>  l
> > ['a', 'b', 'c', 'e']
> > This code is so clean and looks very healthy.  Python will live a
> > long way because its a cute language.
> 
> imho the code is very unhealthy, i would write
> l = ['a', 'b', 'c', 'd', 'e']
> l.remove('d')
> print l
> 
> btw what are you using ';' for

I am learning Python. I used 'for' specifically so that i could
iterate over the list and delete the values. It was a dumb one.. thanx
for pointing it out but i specifically wanted to understand how
slicing work. :-)
thanks anyway.

-- 
cheers,
Ishwor Gurung
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list IndexError

2004-12-22 Thread Egor Bolonev
On Thu, 23 Dec 2004 06:56:02 +1030, Ishwor <[EMAIL PROTECTED]> wrote:
l
['a', 'b', 'c', 'd', 'e']
for x in l[:]:
   if x == 'd':
   l.remove('d');
l
['a', 'b', 'c', 'e']
This code is so clean and looks very healthy.  Python will live a
long way because its a cute language.
imho the code is very unhealthy, i would write
l = ['a', 'b', 'c', 'd', 'e']
l.remove('d')
print l
btw what are you using ';' for
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to start a new process while the other ist running on

2004-12-22 Thread Keith Dart
On 2004-12-22, Erik Geiger <[EMAIL PROTECTED]> wrote:
> Donn Cave schrieb:
>
>> In article <[EMAIL PROTECTED]>, Erik Geiger <[EMAIL PROTECTED]>
>> wrote:
> [...]
>> > Thats what I've tried, but it did not work. Maybe it's because I want to
>> > start something like su -c '/path/to/skript $parameter1 $parameter2' 
>> > user
>
>> Unfortunately this particular case kind of dilutes the advantages
>> of spawnv.  In the common case, parameter1 et al. would be submitted
>> directly as the parameter list.  I believe it may be clearer to start
>> with to think about the spawnv() function -
>>os.spawnv(os.P_NOWAIT, path, [cmdname, parameter1, parameter2])
>> 
>> If one of the parameters is itself another command, then of course
>> it has to be rendered as a string
>>os.spawnv(os.P_NOWAIT, '/bin/su', ['su', '-c', '%s %s %s' % (cmd,
>>   parameter1, parameter2)])
>> so you have almost as much work to scan the parameters for shell
>> metacharacters as you would have with system().
>> 
>>Donn Cave, [EMAIL PROTECTED]
> OK, thats too high for me ;-)
>
> Is the %s the variable for the following commands/parameters? If I have
> three parameters, I'll need one more %s? Where to write the user for the su
> command?
>
> Well, I've given up ;-)
>

Hey, don't give up. There is help. ;-) guess...

There is a package called pyNMS (http://sourceforge.net/projects/pynms)
That has a module called "proctools", and also one called "sudo". Once
you set up sudo correctly, you can do what you want easily. 

However, be aware that proctools spawns a process with the subprocess
stdio connected to _your_ parent process, and does not inherit the stdio
of the parent. So, if the subprocess writes a lot of stuff you must read
it, or the subprocess will block. However, there is some (perhaps buggy)
support for asynchronous operation where those reads happen
automatically (on Linux). 




-- 
-- ~
   Keith Dart <[EMAIL PROTECTED]>
   public key: ID: F3D288E4
   =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Skinnable/Stylable windows in wxPython?

2004-12-22 Thread Daniel Bickett
> > Not only would this make it more multi-platform (I have no access to
> > a GTK machine so I don't know if this works. Could someone please
> > check?)
> 
> Looks like it works (I had to change frame.Show() to frame.Show(1)
> though, but that could be because it's an old version).

No, I think that was a slip on my part when copying the code from one
screen to the next :)

> One odd thing
> though: the Windows version doesn't react to clicking or dragging the
> mouse, which seems to be the expected behavior.

I noted in my second post that the functionality of the window
(clicking and dragging et al) was, even in the wxPopupWindow demo,
implemented by using the EVT macros. Copied from the demo, the code is
as follows:

def OnMouseLeftDown(self, evt):
self.ldPos = evt.GetEventObject().ClientToScreen(evt.GetPosition())
self.wPos = self.GetPosition()
self.CaptureMouse()

def OnMouseMotion(self, evt):
if evt.Dragging() and evt.LeftIsDown():
dPos = evt.GetEventObject().ClientToScreen(evt.GetPosition())
nPos = (self.wPos.x + (dPos.x - self.ldPos.x),
self.wPos.y + (dPos.y - self.ldPos.y))
self.Move(nPos)

def OnMouseLeftUp(self, evt):
self.ReleaseMouse()

def OnRightUp(self, evt):
self.Show(False)
self.Destroy()

> The GTK version can be
> moved by dragging the mouse; even just clicking the mouse moves the
> window somewhat down and to the left.

That's interesting... I wonder if using those methods would conflict
at all. Also, while I'm on that note, when double clicking on the
resulting window (after binding those events), double click causes a
non-fatal, yet annoying, traceback saying that "the mouse could not be
released because it has not yet been caught blah blah", so I just
wrapped the contents of OnMouseLeftUp in a try..except..pass.

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


Re: word to digit module

2004-12-22 Thread M.E.Farmer
Cool script just one little thing,
toNumber('One thousand') bites the dust.
Guess you should add another test, and s.lower() ;)

Stephen Thorne wrote:
{code snip}
> def toNumber(s):
+ s = s.lower()
> items = s.replace(',', '').split()
> numbers = [translation.get(item.strip(), -1) for item in items if
> item.strip()]
> if -1 in numbers:
> raise ValueError("Invalid string '%s'" % (s,))
>
> if 1000 in numbers:
> idx = numbers.index(1000)
> hundreds = numbers[:idx]
> numbers = numbers[idx+1:] + [1000*x for x in hundreds]
>
> if 100 in numbers:
> idx = numbers.index(100)
> hundreds = numbers[:idx]
> numbers = numbers[idx+1:] + [100*x for x in hundreds]
> 
> return sum(numbers)
> 
> Stephen Thorne

M.E.Farmer

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


Help to find a library...

2004-12-22 Thread whamoo
Hello,

I'm looking for a library like ncurses, but that can be used also on
windows in a very simple way...

There is some library that do some like curses?

Thanks a lot

-- 
Whamoo www.rknet.it
Powerd by: MacOsX, Gnu/Linux Debian Sarge,
Amiga Os 3.9, Milk.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MIDI (was - Re: BASIC vs Python)

2004-12-22 Thread JanC
Bob van der Poel schreef:

> Just as a side note, I remember reading somewhere that the Casio WK3000 
> Keyboard uses Python. Not sure if that's internal or just for Casio's 
> own development.



At the bottom it says:
| 2. Python Programming Language  - some of Casio's Internet Data 
| Expansion System is written in Python, a high-level interpreted, 
| interactive, object-oriented programming language (check your PC folder 
| holding the Casio wave converter program - it also holds a file called 
| python22.dll and other files ending in '.pyd' which are Python runtime 
| dlls). Programmers may be able to use Casio's runtime routines to create 
| new utilities for the wk3000.  Python is free to download and use.
| 
| I need someone to look inside the various runtime dll's and Python pyd's 
| and report back on what they discover...


-- 
JanC

"Be strict when sending and tolerant when receiving."
RFC 1958 - Architectural Principles of the Internet - section 3.9
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Garbage collector strategy

2004-12-22 Thread "Martin v. Löwis"
Martin Drautzburg wrote:
Just for curiosity: does python use a mark-and-sweep garbage collector
or simple reference counting? 
I can't resist: Yes, it does.
In the latter case it would not garbage
collect circular references, right ?
Python uses refcounting for all objects, and a generational collector
for container objects.
For mark-and-sweep, I assume there must be a toplevel Object from
which all other objects can be accessed or they will be GCed (called
"Smalltalk" in Smalltalk). Is there such a thing?
No. There are no gc roots. Instead, there are global lists of all
container objects, sorted by generation. Garbage is what is not
referenced from outside these lists, everything else must be rooted
somewhere (either in a true root, a local variable of some stack
frame, or an older generation)
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: mathmatical expressions evaluation

2004-12-22 Thread beliavsky
Paul McGuire wrote:
>And I wouldn't necessarily agree with beliavsky's assertion that
numarray
>arrays are needed to represent payment dates and amounts, unless you
were
>going to implement a major banking financial system in Python.

Maybe arrays are not "needed", but especially for vectors of floating
point numbers, I prefer to use a Numeric array rather than a list
because

(1) array operations like sum and exp are possible, and I want z = x +
y to perform an element-wise sum rather than a concatenation of lists.
Given arrays containing a set of times, coupon amounts, and interest
rates, the value of a bond could be a calculated with a single
expression, without loops.

(2) A TypeError is raised if I do something illogical like

x = zeros(3,Float)
x[0] = "dog"

(3) Higher-dimensional arrays are better represented with Numeric or
Numarray arrays than with lists.

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


Re: mathmatical expressions evaluation

2004-12-22 Thread John Machin

Paul McGuire wrote:
> Here's
> a simple loan amortization schedule generator:
>
> def amortizationSchedule( principal, term, rate ):
> pmt = ( principal * rate * ( 1 + rate)**term ) / (( 1 +
rate)**term - 1)

Simpliciter:
pmt = principal * rate / (1 - (1 + rate)**(-term))

> pmt = round(pmt,2)  # people rarely pay in fractional pennies
> remainingPrincipal = principal
> for pd in range(1,term+1):
> if pd < term:
> pdInterest = rate * remainingPrincipal
> pdInterest = round(pdInterest,2)
> pdPmt = pmt
> else:

Huh? You don't charge interest in the last period? I'd like to apply
for a loan of $1B for a term of one month with monthly repayments.

> pdInterest = 0
> pdPmt = remainingPrincipal
> pdPrincipal = pdPmt - pdInterest
> remainingPrincipal -= pdPrincipal
> yield pd, pdPmt, pdInterest, pdPrincipal, remainingPrincipal
>

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


Re: Problem with msvcrt60 vs. msvcr71 vs. strdup/free

2004-12-22 Thread "Martin v. Löwis"
[EMAIL PROTECTED] wrote:
Believe it or not I do not get a crash here.
I can believe this. strdup does malloc, i.e. gets some
memory from the heap, and free puts it back into the heap.
Since this is a different CRT, it puts it back into
a different heap. This is a leak, but it should not cause
a crash.
I have a gut feeling that "DLLs" here does not mean inter-dll passing
of resources, but intra-dll passing of resources. In other words that
if the self-same DLL uses both run-times then you are in trouble; but I
don't think that this relates to the situation where one DLL is using
msvcrt and another DLL is using msvcr71. Please bear with me.
I think you are wrong. What DLL invokes the CRT function does not matter
- that the CRT functions come from different DLLs matters. Each CRT
is loaded exactly once into an address space, regardless of how many
DLLs refer to it. However, different CRTs have different sets of global
variables, and this is what hurts.
E.g. malloc use a pointer to the free list in the heap, and so does
free. Each CRT has its own heap, and each has its own pointer to the
free list. Then, doing malloc in one CRT and free in the other does
not cause crashes (perhaps unless you use the debug CRT, which tries
to determine whether it owns the pointer being freed). The CRT will
put the memory into its own free list, and allocate it again if its
own malloc asks for it. However, if you repeatedly do malloc() in one
CRT and free() in another, you get a memory leak, since malloc() will
not find the memory that has been freed.
In this light, I truly don't know why would we try, or recommend
others, to link with libmsvcr71.a, if some mix-up is still possible. I
have yet to see a crash occur when Python24.dll or an extension of the
same uses the old way of  linking with libmsvcrt.a. That way we are
assured that no references are made to msvcr71 when msvcrt is the one
used when linking.
This is very easy to create. Just do fopen() in an extension linked
with msvcrt.dll, then do PyRun_AnyFile. This will crash, because fread()
on a file opened in a different CRT will always crash.
I could be mistaken, but I think people are confusing the behavior of
the MS compilers with MinGW's. The old MS compiler (V. 6) uses
msvcrt.lib by default, and even when the newer MSVS uses the same name
for the its default runtime, that msvcrt link implicitly means the
newer msvcr71 [2].
You are mistaken. The name of the import library is, and always was,
msvcrt.lib. However, different versions of msvcrt.lib refer to different
DLLs: msvcrt40.dll, msvcr70.dll, and msvcr71.dll.
> This behind the scenes behavior is what seems to
have people mixed up. You see if one has older projects compiled using
V. 6, then linking these object files to other object files compiled
with the newer MSVS could effectively mean that the resulting DLL will
have references to both run-times, something by the way is also
mentioned in the MSDN resources [3].
I think you are misreading [3]: It explicitly says
"If you have a .lib or .obj file that needs to link to msvcrt.lib, then
you should *not* have to recompile it to work with the new msvcrt.lib in
Visual C++ .NET." (emphasis mine)
The only case where you can link a single DLL with different CRTs using
MS tools is when you combine different versions of the CRTs, e.g. debug
and non-debug, or DLL and non-DLL.
But as far as I know this is not the case with regards to MinGW. MinGW
explicitly uses msvcrt, and so old and newer projects should in theory
have no problems if they stick to msvcrt, as opposed to going the MS
compilers' path-- shooting ourselves in the foot-- and risking linking
to two run-times at the same time.
Python extensions should never ever link with msvcrt.dll. As your
reference says:
'The msvcrt.dll is now a "known DLL," meaning that it is a system 
component owned and built by Windows. It is intended for future use only 
by system-level components. An application should use and redistribute 
msvcr71.dll'

Now, a Python extension is released from the need to distribute
msvcr71.dll, since Python already does that. It should still link
with that DLL.
I have tried changing the specs, and changing the location of msvcr71
and the results are never 100% re-assuring. And so I have resorted to
linking with the good old msvcrt and I have not had a crash due to this
to date. Of course this is my humble experience and I could be mistaken
big time.
You are.
For what it is worth, however, my extension DLLs are clean in that they
reference msvcrt only and not msvcr71, and hence all the malloc, and
free and what have you are never shared with any other runtime. 
How do you know? What if your extension returns a pointer malloc'ed by
msvcrt.dll, and returns it to python24.dll, and then python24.dll
frees the pointer, using free() from msvcr71.dll?
My
point being that lacking empirical evidence to the contrary, I think
this is how making extensions to Python 2.4 with MinGW should be: using
the default runtime

Killing a python thread with a signal

2004-12-22 Thread James Lamanna
So I've created a thread with the threading.Thread class, but I want to 
be able to kill this thread because it does a select() with a timeout of 
None.

Is there any way to send a signal only to this thread and wake it up 
from the select?

Thanks.
Please CC me for I am not subscribed.
--
James Lamanna
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie namespace question

2004-12-22 Thread Brandon
Peter,

You're correct about the bug.  I did need a 'self' parm...  I was just
winging the example because the actual code is pretty large.  I'm using
google groups for my posting and it didn't carry spaces through (I did
use spaces and not tabs).

The "fix" or workaround was to import __builtin__ and add the
AdminConfig reference there in configure_server_foo.py as follows:

import __builtin__
__builtin__.AdminConfig = AdminConfig

As for the indentations, substitute ~ with a space.

Hopefully, a bug free and "indented" version.  :)

#jdbc.py
class DataSource:
~~~def __init__(self, servername):
~~self.servername = servername

~~~def create(self, name, connectionInfo, etc):
~~#Call the IBM supplied WebSphere config object
~~AdminConfig.create('DataSource')

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


Re: how to start a new process while the other ist running on

2004-12-22 Thread Erik Geiger
Donn Cave schrieb:

> In article <[EMAIL PROTECTED]>, Erik Geiger <[EMAIL PROTECTED]>
> wrote:
[...]
> > Thats what I've tried, but it did not work. Maybe it's because I want to
> > start something like su -c '/path/to/skript $parameter1 $parameter2' 
> > user

> Unfortunately this particular case kind of dilutes the advantages
> of spawnv.  In the common case, parameter1 et al. would be submitted
> directly as the parameter list.  I believe it may be clearer to start
> with to think about the spawnv() function -
>os.spawnv(os.P_NOWAIT, path, [cmdname, parameter1, parameter2])
> 
> If one of the parameters is itself another command, then of course
> it has to be rendered as a string
>os.spawnv(os.P_NOWAIT, '/bin/su', ['su', '-c', '%s %s %s' % (cmd,
>   parameter1, parameter2)])
> so you have almost as much work to scan the parameters for shell
> metacharacters as you would have with system().
> 
>Donn Cave, [EMAIL PROTECTED]
OK, thats too high for me ;-)

Is the %s the variable for the following commands/parameters? If I have
three parameters, I'll need one more %s? Where to write the user for the su
command?

Well, I've given up ;-)

Thanks for the explanation!

Erik
-- 
Jemanden wie ein rohes Ei zu behandeln kann auch bedeuten, ihn in die Pfanne
zu hauen.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BASIC vs Python

2004-12-22 Thread Andrew Dalke
Jan Dries:
> The funny thing is, for me, MIDI is dead old. One of my first computers, 
> back in 1986, was an Atari ST. It came equiped with a MIDI port.

While the time I was talking about was some 3 or 4 years
before 1986.  

> I seem to remember that even then we still had to rely on a keyboard or 
> so to do the playback.

And my memory was the Midi was this expensive thing that required
specialized hardware that (almost?) no one I knew had.

> But nowadays even the cheapest PC comes with "multi-media" sound 
> hardware, and playback of MIDI files is easy.

Which I think agrees with my belief that my knowledge of
computer sound is so historical that I can't make a
strong statement of what I would like in a modern library.

> Frankly I share your sentiment and "these newer things" like sound 
> clips, mixers, recording software and so have never managed to 
> interested me either.

I heard a really fun song at a student concert once.  The
musician played the same basic few bars on the electric ukulele
but really played with the downstream effects, like reverb
and delay.  At its peak there were so many modified copies of
the basic song being played that it was hard to pick out any
one of them.  The auditorium was filled with sound.  That piece
got the biggest applause of the evening.

I mention this because I can see how sound effects networks
would also be fun to have in a sound library.  What I don't
know is the tradeoff between the different factors: optimize
for programmers like me?  For beginning programmers?  For
people interested in creating new songs?  Those interested
in experimenting with atonal music?  Those who want to do
mashups?  Karaoke enthusiasts?  In looking around at the modern
libraries, one supported 3D placement of the audio.  I hadn't
even thought of that ability.

Andrew
[EMAIL PROTECTED]

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


RE: Metaclasses

2004-12-22 Thread Robert Brewer
Bob Cowdery wrote:
> What I want to do is when
> 
> class API(object):
> __metaclass__ = MetaAPI
> 
> is created that MetaAPI generates attributes from a given
> capability map and not the one it picked up on 'import'.

Okay. It depends on where you're getting that capability information from, but 
the simplest approach I can think of would be to stick it in the class:

class API(object):
__metaclass__ = MetaAPI

capmap = global_map_getter(usercontext_or_keyring)

...then "capmap" should be available within MetaAPI.__init__:

class MetaAPI(type):
def __init__(cls, name, bases, dct):
for name, method in dct['capmap']:
setattr(cls, name, method)

Of course, all of this could be done without using a metaclass--just call 
setattr as needed right after your class is defined. Another option would be to 
immediately follow your API class definition with a call like:

from myframework import captools

class API(object):
def foo():
pass

captools.enable(API)


...the choice comes down IMO to what you think will be the most 
usable/maintainable by those who follow you.


Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: extract news article from web

2004-12-22 Thread Steve Holden
Steve Holden wrote:
[...]
However, the code to extract the news is pretty simple. Here's the whole 
 program, modulo newsreader wrapping. It would be shorter if I weren't 
stashing the extracted links it a relational database:

[...]
I see that, as is so often the case, I only told half the story, and you 
will be wondering what the "db" module does. The main answer is adapts 
the same logic to two different database modules in an attempt to build 
a little portability into the system (which may one day be open sourced).

The point is that MySQLdb requires a "%s" in queries to mark a 
substitutable parameter, whereas mxODBC requires a "?". In order to work 
around this difference the db module is imported by anything that uses 
the database. This makes it easier to migrate between different database 
technologies, though still far from painless, and allows testing by 
accessing a MySQL database directly and via ODBC as another option.

Significant strings have been modified to protect the innocent.

#
# db.py: establish a database connection with
#the appropriate parameter style
#
try:
import MySQLdb as db
conn = db.connect(host="", db="",
 user="", passwd="")
pmark = "%s"
print "Using MySQL"
except ImportError:
import mx.ODBC.Windows as db
conn = db.connect("", user="", password="")
pmark = "?"
print "Using ODBC"

regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


a question about socket objects

2004-12-22 Thread Dag Hansteen



Hello,
 
I have a question:
How do I append a socket object into a list 
"manually" without appending the variable which the socket object is stored in, 
but just the socket object itself if I somehow 
know the address(pretend like)? 
I dont "need" this in any way for my code, but I 
would like to know, for a better understanding of network 
programming
 
I know how to do it like 
"socketobject, addr = sock.accept()".
Then append socketobject to that list
 
But if we just pretend like I know that 
the socketobject is , how can I 
append this socket._socketobject to the list? 
like list.append() ??? 
 
Thats what I want to know, not that I need it, but 
I'm curious to know how python handles/work with the socket objects in 
general
 
Any answer or explanation is 
greatly appreciated!
 
Best regards
Dag Hansteen
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Newbie namespace question

2004-12-22 Thread Peter Hansen
Brandon wrote:
Thanks, that worked to get me past the "problem".  Did you see my post
regarding my issue?  I just know that there's a "Python way" to resolve
my issue, so if anyone has a better way, I'm really interested.
Not only does it feel like a hack, it looks like one too!  Even worse!
If you mean the one you describe in your post with the Jython
code, I can't help, mainly because I can't parse it.  For
one thing I think you are using TABs instead of spaces, and
many newsreaders will eliminate leading tabs so it makes the
code pretty hard to decipher.  I could probably figure it out
anyway, except that I think you have a bug as well:
#jdbc.py
class DataSource:
def __init__(self, servername):
self.servername = servername
def create(name, connectionInfo, etc):
#Call the IBM supplied WebSphere config object
AdminConfig.create('DataSource')
This is how it looked to me.  The presumed bug is in the "create"
method definition, where you are not supplying a "self" parameter.
At least, I assume that is a method of DataSource and not
a module-level function, because in the previous code you were
trying to call ds.create() where ds was a DataSource object.
I'd probably have some ideas if you reposted with leading
spaces and explained or fixed the supposed bug.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python for Series 60 update

2004-12-22 Thread Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.
Hi !

Thanks ; and good news : I, finally, could register me into the Nokia's
forums, and I, finally, could to download the package.

@-salutations
-- 
Michel Claveau




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


Re: Newbie namespace question

2004-12-22 Thread Peter Hansen
deelan wrote:
i believe that to avoid circular refs errors remember you can 
lazy-import,  for example here i'm importing the email package:

m = __import__('email')
m

check help(__import__) for futher details.
I'm not sure what you think that does, but I don't
think it does it.
The code you show above is no more "lazy" than a simple
"import email as m" would have been, I believe.
All statements are executed as they are encountered
during import, so any that are no inside a function
or class definition, or protected by a conditional
control structure in some way, will be executed right
away, rather than lazily.
I may have misinterpreted what you were trying to say...
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: list IndexError

2004-12-22 Thread Ishwor
On Wed, 22 Dec 2004 14:59:32 -0500, Mike C. Fletcher
<[EMAIL PROTECTED]> wrote:

[snip]

>
> Probably the most pythonic approach to this problem when dealing with
> small lists is this:
>
>result = [ item for item in source if item != 'e' ]
>
> or, if you're using an older version of Python without list comprehensions:
>
>filter( lambda item: item!='e', source )
>

I believe lamda's are unnamed functions aren't they?? Still learning... ;-)

> or even (expanding the list comprehension):
>
>result = []
>for item in source:
>   if item != 'e':
>  result.append( item )
>
> The "python"-ness of the solutions is that we are using filtering to
> create a new list, which is often a cleaner approach than modifying a
> list in-place.  If you want to modify the original list you can simply
> do source[:] = result[:] with any of those patterns.
>

yeah actually i saw what Fedrik had to say above. I created a sliced
copy of the l & did my homework within the for loop

>>> l
['a', 'b', 'c', 'd', 'e']
>>> for x in l[:]:
   if x == 'd':
   l.remove('d');

>>> l
['a', 'b', 'c', 'e']

This code is so clean and looks very healthy. :) Python will live a
long way because its a cute language. :-)

> If you really do need/want in-place modification, these patterns are
> quite serviceable in many instances:
>
># keep in mind, scans list multiple times, can be slow
>while 'e' in source:
>   source.remove('e')
>
> or (and this is evil C-like code):
>
>for index in xrange( len(source)-1, -1, -1 ):
>   if source[i] == 'e':
>  del source[i]
> 
thanx Mike, i have tried this C-ish way as well . :-) it seemed quiete
ok for my  small list but dont know about huge lists.

> Keep in mind that, in the presence of threading, any index-based scheme
> is likely to blow up in your face (even the filtering solutions can
> produce unexpected results, but they are generally not going to raise
> IndexErrors due to off-the-end-of-the-list operations).
>

Every 2-4 hours i check the c.l.py ... Its so nice that i learn new
things everyday in this list.. (some are goood but some are extremely
subjective!!)
Lastly i personally feel that Python's way of trying things out before
implementing is really healthy way of programming. Especially towards
XP oriented projects. :-)

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


Re: extract news article from web

2004-12-22 Thread Steve Holden
Zhang Le wrote:
Hello,
I'm writing a little Tkinter application to retrieve news from
various news websites such as http://news.bbc.co.uk/, and display them
in a TK listbox. All I want are news title and url information. Since
each news site has a different layout, I think I need some
template-based techniques to build news extractors for each site,
ignoring information such as table, image, advertise, flash that I'm
not interested in.
So far I have built a simple GUI using Tkinter, a link extractor
using HTMLlib to extract HREFs from web page. But I really have no idea
how to extract news from web site. Is anyone aware of general
techniques for extracting web news? Or can point me to some falimiar
projects.
I have seen some search engines doing this, for
example:http://news.ithaki.net/, but do not know the technique used.
Any tips?
Thanks in advance,
Zhang Le
Well, for Python-related news is suck stuff from O'Reilly's meerkat 
service using xmlrpc. Once upon a time I used to update 
www.holdenweb.com every four hours, but until my current hosting 
situation changes I can't be arsed.

However, the code to extract the news is pretty simple. Here's the whole 
 program, modulo newsreader wrapping. It would be shorter if I weren't 
stashing the extracted links it a relational database:

#!/usr/bin/python
#
# mkcheck.py: Get a list of article categories from the O'Reilly Network
#   and update the appropriate section database
#
import xmlrpclib
server = 
xmlrpclib.Server("http://www.oreillynet.com/meerkat/xml-rpc/server.php";)

from db import conn, pmark
import mx.DateTime as dt
curs = conn.cursor()
pyitems = server.meerkat.getItems(
{'search':'/[Pp]ython/','num_items':10,'descriptions':100})
sqlinsert = "INSERT INTO PyLink (pylWhen, pylURL, pylDescription) 
VALUES(%s, %s, %s)" % (pmark, pmark, pmark)
for itm in pyitems:
description = itm['description'] or itm['title']
if itm['link'] and not ("<" in description):
curs.execute("""SELECT COUNT(*) FROM PyLink
   WHERE pylURL=%s""" % pmark, (itm['link'], ))
newlink = curs.fetchone()[0] == 0
if newlink:
print "Adding", itm['link']
curs.execute(sqlinsert,

(dt.DateTimeFromTicks(int(dt.now())), itm['link'], description))
conn.commit()
conn.close()
Similar techniques can be used on many other sites, and you will find 
that (some) RSS feeds are a fruitful source of news.

regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression: perl ==> python

2004-12-22 Thread John Machin

Fredrik Lundh wrote:
> "JZ" wrote:
>
> > >> import re
> > >> line = "The food is under the bar in the barn."
> > >> if re.search(r'foo(.*)bar',line):
> > >>   print 'got %s\n' % _.group(1)
> > >
> > > Traceback (most recent call last):
> > >   File "jz.py", line 4, in ?
> > > print 'got %s\n' % _.group(1)
> > > NameError: name '_' is not defined
> >
> > I forgot to add: I am using Python 2.3.4/Win32 (from
ActiveState.com). The
> > code works in my interpreter.
>
> only if you type it into the interactive prompt.  see:

No, it doesn't work at all, anywhere. Did you actually try this?

>
>
http://www.python.org/doc/2.4/tut/node5.html#SECTION00511
>
> "In interactive mode, the last printed expression is assigned to
the variable _.
> This means that when you are using Python as a desk calculator,
it is some-
> what easier to continue calculations /.../"
>

In the 3 lines that are executed before the exception, there are *no*
printed expressions.

Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> line = "The food is under the bar in the barn."
>>> if re.search(r'foo(.*)bar',line):
... print 'got %s\n' % _.group(1)
...
Traceback (most recent call last):
File "", line 2, in ?
NameError: name '_' is not defined
>>>

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


Re: mathmatical expressions evaluation

2004-12-22 Thread Paul McGuire
"Tonino" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hi,
>
> I have a task of evaluating a complex series (sorta) of mathematical
> expressions and getting an answer ...
>
> I have looked at the numarray (not really suited??) and pythonica (too
> simple??) and even tried using eval() ... but wondered if there were
> other packages/modules that would enable me to to this a bit easier...
>
> The formula/equations are for investment calculations (Swap Yields).
> Is there a module/method that anyone can suggest ??
>
> Many thanks
> Tonino
>
Is it a financial analysis library you are looking for, or an expression
parser?

You will find a basic expression parser included in the examples with the
pyparsing.  This parser can be easily extended to add built-in functions,
additional operators, etc.  (You can download pyparsing at
http://pyparsing.sourceforge.net.)

What does one of these complex mathematical functions look like, anyway?

And I wouldn't necessarily agree with beliavsky's assertion that numarray
arrays are needed to represent payment dates and amounts, unless you were
going to implement a major banking financial system in Python.  You can
easily implement payment schedules using lists, or even generators.  Here's
a simple loan amortization schedule generator:

def amortizationSchedule( principal, term, rate ):
pmt = ( principal * rate * ( 1 + rate)**term ) / (( 1 + rate)**term - 1)
pmt = round(pmt,2)  # people rarely pay in fractional pennies
remainingPrincipal = principal
for pd in range(1,term+1):
if pd < term:
pdInterest = rate * remainingPrincipal
pdInterest = round(pdInterest,2)
pdPmt = pmt
else:
pdInterest = 0
pdPmt = remainingPrincipal
pdPrincipal = pdPmt - pdInterest
remainingPrincipal -= pdPrincipal
yield pd, pdPmt, pdInterest, pdPrincipal, remainingPrincipal

# print amortization schedule for $10,000 loan for 3 years at 6% annual
P = 1
Y = 3
R = 6.00
for (i, pmt, int, princ, remaining) in amortizationSchedule(P, Y*12,
R/100.0/12.0):
print i, pmt, int, princ, remaining

print

def aprToEffectiveApr(apr):
apr /= 1200.0
return round(((1+apr)**12-1) * 100, 2)

APR = R
print "Nominal APR of %.2f%% is an effective APR of %.2f%%" % (APR,
aprToEffectiveApr(APR) )

prints out (rather quickly, I might add):
1 304.22 50.0 254.22 9745.78
2 304.22 48.73 255.49 9490.29
3 304.22 47.45 256.77 9233.52
4 304.22 46.17 258.05 8975.47
5 304.22 44.88 259.34 8716.13
6 304.22 43.58 260.64 8455.49
7 304.22 42.28 261.94 8193.55
8 304.22 40.97 263.25 7930.3
9 304.22 39.65 264.57 7665.73
10 304.22 38.33 265.89 7399.84
11 304.22 37.0 267.22 7132.62
12 304.22 35.66 268.56 6864.06
13 304.22 34.32 269.9 6594.16
14 304.22 32.97 271.25 6322.91
15 304.22 31.61 272.61 6050.3
16 304.22 30.25 273.97 5776.33
17 304.22 28.88 275.34 5500.99
18 304.22 27.5 276.72 5224.27
19 304.22 26.12 278.1 4946.17
20 304.22 24.73 279.49 4666.68
21 304.22 23.33 280.89 4385.79
22 304.22 21.93 282.29 4103.5
23 304.22 20.52 283.7 3819.8
24 304.22 19.1 285.12 3534.68
25 304.22 17.67 286.55 3248.13
26 304.22 16.24 287.98 2960.15
27 304.22 14.8 289.42 2670.73
28 304.22 13.35 290.87 2379.86
29 304.22 11.9 292.32 2087.54
30 304.22 10.44 293.78 1793.76
31 304.22 8.97 295.25 1498.51
32 304.22 7.49 296.73 1201.78
33 304.22 6.01 298.21 903.57
34 304.22 4.52 299.7 603.87
35 304.22 3.02 301.2 302.67
36 302.67 0 302.67 0.0

Nominal APR of 6.00% is an effective APR of 6.17%


-- Paul


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


RE: Best GUI for small-scale accounting app?

2004-12-22 Thread Gabriel Cosentino de Barros
Title: RE: Best GUI for small-scale accounting app?





> I went w/wxPython for a second app because of its printing capabilities
> and the large number of controls that come with it.  Otherwise I would
> use pyFltk for small apps.


does FLK has any good positioning model now? Last time i checked i could only put something in pixel(sic) x=10, y=10, width=100, height=100.

It's awfull because you have to write window resize code (argh) and the widgets doesn't repect the font size if said user is using a resolution like 1900x1600 with DPI of almost 300 (my case hehe). Since your testing enviroment probably was 800x600 with a DPI of no more then 100 you'r big screen user will have fonts 1/3 of the desired size.




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

Re: list IndexError

2004-12-22 Thread Mike C. Fletcher
Ishwor wrote:
i am trying to remove an item 'e' from the list l but i keep getting IndexError.
I know the size of the list l is changing in the for loop & its sort
of trivial task but i found no other way than to suppress the
IndexError by doing a pass. any other ways you guys can suggest? Also
is this a good or bad habit in Python? someone may perhaps suggest a
better way which i am unaware of?? the deletion could be invoked from
user input (command line) as well so its not limited to 'e'( as in my
code)
 

Probably the most pythonic approach to this problem when dealing with 
small lists is this:

   result = [ item for item in source if item != 'e' ]
or, if you're using an older version of Python without list comprehensions:
   filter( lambda item: item!='e', source )
or even (expanding the list comprehension):
   result = []
   for item in source:
  if item != 'e':
 result.append( item )
The "python"-ness of the solutions is that we are using filtering to 
create a new list, which is often a cleaner approach than modifying a 
list in-place.  If you want to modify the original list you can simply 
do source[:] = result[:] with any of those patterns.

If you really do need/want in-place modification, these patterns are 
quite serviceable in many instances:

   # keep in mind, scans list multiple times, can be slow
   while 'e' in source:
  source.remove('e')
or (and this is evil C-like code):
   for index in xrange( len(source)-1, -1, -1 ):
  if source[i] == 'e':
 del source[i]
Keep in mind that, in the presence of threading, any index-based scheme 
is likely to blow up in your face (even the filtering solutions can 
produce unexpected results, but they are generally not going to raise 
IndexErrors due to off-the-end-of-the-list operations).

Good luck,
Mike

 Mike C. Fletcher
 Designer, VR Plumber, Coder
 http://www.vrplumber.com
 http://blog.vrplumber.com
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >