Re: word to digit module

2004-12-22 Thread Fredrik Lundh
Stephen Thorne wrote:

>> Is there any module available that converts word like 'one', 'two',
>> 'three' to corresponding digits 1, 2, 3??
>
> This seemed like an interesting problem! So I decided to solve it.

> for i in range(4):

that's a slightly unusual definition of "digit", but it's a nice script, and
an excellent illustration of pragmatic test-driven development, so who
am I to complain?

 



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


Re: Python To Send Emails Via Outlook Express

2004-12-22 Thread ian
Hi Lenard,
Absolutely fantastic!!
That worked like a charm.
Now onto adapting it to send attachments.

Thanks again

Ian

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


Re: lies about OOP

2004-12-22 Thread Steve Holden
Fredrik Lundh wrote:
Paul Foley wrote:
That's because their language is derived from Serbo-Croat.
No it isn't.

time to tune your "absurd humour" sensor somewhat slightly?  I thought
the next sentence was a pretty obvious giveaway:
"But both the Finns and the Swedes will tell you it's the
Norwegians who are alcoholics."
;-)
--
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: Why are tuples immutable?

2004-12-22 Thread Antoon Pardon
Op 2004-12-21, Jeff Shannon schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:
>
>>Op 2004-12-21, Nick Coghlan schreef <[EMAIL PROTECTED]>:
>>  
>>
>>>Antoon Pardon wrote:
>>>
>>>
Why then doesn't python think the same about sorted lists. When I have a
sorted list and do operations on it that depend on it being sorted,
I can mess things up just as easily by mutating an element in that
sorted list as I can mess things up by mutating a dictionary key.
  

>>>Incorrect, and this appears to be the point where our major disagreement 
>>>lies.
>>>
>>>Mutate a value in a sorted list and you can fix that easily, just by calling 
>>>its 
>>>sort() method again (and, in fact, mutate and resort is a fairly common 
>>>idiom 
>>>for small datasets). 'sorted' and 'heapified' are list properties that are 
>>>easily broken by direct manipulation, but are also easily restored by once 
>>>again 
>>>'sorting' or 'heapifying'.
>>>
>>>
>>
>>That is an implemantation detail. Likewise a dictionary is probably not
>>always in a sane state when a new key is inserted. The fact remains that
>>in a sorted list or a heap, mutating an element arbitrarily can mess up
>>things greatly.
>>  
>>
>
> These comparisons to sorted lists and heaps are a red herring.  The 
> analogous situation to those is dictionary *values*, not dictionary keys 
> -- in essence, the "keys" of a list (whether sorted or not) are integers. 

No it is not a red herring. The analogy is not in the fact that sorted
lists have keys, but that sorted lists and heapqueues have an invariant
just like dictionary keys and that this invariant can be violated by
mutating the objects just as the dictionary invariant can be violated
by mutating a key. That sorted lists have keys too is just an
insignificant coincidense here.

>>>Change the hash value of an item used as a key in a dictionary, and *the 
>>>internal state of the dictionary is likely to broken in a manner you 
>>>probably 
>>>cannot fix*. The only reason the 'probably' is there is because you should 
>>>be 
>>>able to 'fix it' by changing the hash value back to what it was originally.
>>>
>>>
>>
>>I could argue that this is then a failing of dictionary that doesn't
>>provide a method to clean up after a key is mutated.
>>  
>>
>
> So show us a dictionary (i.e. hash table) implementation that can do 
> this.

Why should I, Do you doubt that it is possible?

> You'll need to be able to derive the old hash from the new hash, 
> of course, so that you can correctly associate the values already stored 
> under that key.  And you'll have to be able to do that without referring 
> to the pre-modified object again, because dicts can't track every Python 
> operation that might modify a key object.  And it needs to deal properly 
> with equivalent-but-different-ID list literals, because using literals 
> (and not references stored elsewhere) is an important and common dict 
> key usage.
>
> If you can show me how you plan to accomplish this, I'll accept that 
> you're right on this.  Until then...

I don't have to accomplish all that in order to be able to clean up
a mutated dictionary key. All I need to do is go over the keys, see
if they hash to the same bucket as they are in now and otherwise
put them in the new bucket. Sure that would be costly, but so would
allowing arbitrary mutation in a sorted list and resorting everytime
or in a heapqueue and reheapifying.

>>>Waitasec - wouldn't it be easier if dictionaries just made it a rule that 
>>>the 
>>>hash value wasn't allowed to change? Hang on, that's exactly what they do.
>>>
>>>
>>
>>No it is not.
>>  
>>
>
> Seems to me that the docs are pretty clear on that.  It's true that 
> dictionaries can't enforce that the hash value never change over the 
> entire life of an object, because dicts can only take enforcement 
> actions when the dict itself is referenced -- but that's *why* it's 
> documented.

>>And yes I know what to do if I want to use mutable keys as objects. I'm
>>just argueing against those who think that should be somehow forbidden.
>>  
>>
>
> We're not arguing that it should be arbitrarily forbidden.  We're 
> arguing that doing anything else makes it impossible to behave 
> sensibly.

How does having stable keys in a mutable objects makes it impossible
to behave sensible for dictionaries?

> So prove us wrong,

I don't have to prove you wrong. If you want to argue something,
you have to provide reasoning that shows you right.

> by implementing something that behaves 
> sensibly in the face of mutating keys (which compare by value, as lists 
> do, rather than by identity).

You are confusing two things with each other. That is 1) a mutable object
that is a key and 2) a mutating key. Even if an object is mutable it can
be stable for some duration and thus unmutating. There is IMO nothing
wrong with using such mutable objects as dictionary keys or in other
structures that require an invariant. Requiring that su

Re: Why are tuples immutable?

2004-12-22 Thread Antoon Pardon
Op 2004-12-21, Fredrik Lundh schreef <[EMAIL PROTECTED]>:
> Jeff Shannon wrote:
>
>> So show us a dictionary (i.e. hash table) implementation that can do this.  
>> You'll need to be able 
>> to derive the old hash from the new hash, of course, so that you can 
>> correctly associate the 
>> values already stored under that key.  And you'll have to be able to do that 
>> without referring to 
>> the pre-modified object again, because dicts can't track every Python 
>> operation that might modify 
>> a key object.  And it needs to deal properly with 
>> equivalent-but-different-ID list literals, 
>> because using literals (and not references stored elsewhere) is an important 
>> and common dict key 
>> usage.
>
> and to temporarily refer back to the top of this thread, do all this without
> any performance impact, compared to the current implementation.
>
Why should that be? This originated when someone argued that lists could
easily be resorted and reheapified. But resorting en reheapifying is has
an extra cost to compared to keeping your list sorted or as a heap by
not allowing the elements to be mutated.

So why should violating and repairing invariants be allowed to have a
performance inpact, except when it is done with dictioary keys.

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


Re: Why are tuples immutable?

2004-12-22 Thread Fredrik Lundh
Antoon Pardon wrote:

>> and to temporarily refer back to the top of this thread, do all this without
>> any performance impact, compared to the current implementation.
>>
> Why should that be? This originated when someone argued that lists could
> easily be resorted and reheapified.

from the original post (by someone else):

The way I see it is that if we enable __setitem__ for tuples there
doesn't seem to be any performance penalty if the users don't use it
(aka, python performance independent of tuple mutability).

to which you later added:

The performace gained by using tuples as keys in dictionaries is
entirely illusional.

etc.  am I the only one one this list that can hold more than one post in my
head and chew gum at the same time?

 



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


Re: Why are tuples immutable?

2004-12-22 Thread Antoon Pardon
Op 2004-12-21, Jeff Shannon schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:
>
>>Op 2004-12-17, Jeff Shannon schreef <[EMAIL PROTECTED]>:
>>  
>>
>>>Now, even if hash were made to equal id... suppose I then pass that dict 
>>>to a function, and I want to get the value that I've stored under 
>>>[1,2].  In order to do that, I'd *also* have to pass in the *exact* list 
>>>that I used as the key, because *only* that *exact* instance will hash 
>>>correctly.
>>>
>>>
>>
>>Maybe that is what I want.
>>  
>>
>
> Then use a class instance, rather than a list.  It's too valuable 
> elsewhere to have lists that compare by value rather than identity.

That doesn't answer your original objections. Using a class instance
instead of a list, will not make it any less strange to have two
instance be unequal when all components are equal.

>>That doesn't change the fact that conceptually a programmer can use
>>them that way. So do you think that if a programmer uses a list
>>as a heap or a sorted list he should limit his object to immutable
>>objects. Are you saying that programmers shouldn't sort mutable
>>objects.
>>  
>>
>
> I'm saying that your analogy of list/heap *values* to dictionary *keys* 
> is a bogus analogy.  Dictionary *values* have no restrictions against 
> mutation, just as list/heap values have no restrictions.

Yes a heapqueue has restricions. A heapqueue has an invariant among
its elements and that invariant can be violated if you mutate them.

The same when a list is sorted. The list then has an invariant and
that invariant can be violated by mutating the elements.

> I'm also saying that a sorted/heaped list can be easily fixed by 
> examining the items in it.  A broken hash table *cannot* be fixed that 
> way. 

Yes it can. You can go over the keys and see if the hash puts them in
the same buckets as they are already in and move them if they are not.

>>>Note also that, if a list becomes unsorted or unheaped, it's fairly easy 
>>>to resort or re-heapify the list.  It may take some time, but nothing is 
>>>lost.  If a dictionary key mutates, then data *is* lost. 
>>>
>>>
>>
>>Is it? I don't see why an items method should fail to provide all (key,
>>value) pairs even when keys were mutated.
>>  
>>
>
> How does the dict know which value is associated with which key? 

Because there is a link between the key and the value. The problem
with a mutated key in a dictionary is not that the link between the
key and the value is severed, but that the key hashes now to a different
bucket. But if you just go over the buckets and iterate over the keys
within and there associated values, you will encouter your mutated
key with its value.

> I need to be able to access sequence-keyed dictionaries with literals, 
> which means that the keys need to compare by value, not ID.  Thus, I 
> need to have sequences that compare (and hash) by value.  These 
> conditions *cannot* be met by a mutable list.

Which condition can't be met by a mutable list? The only ones I see
above is comparison and hashable by value. A list can be compared
and hashed by value.

> I can have the quality of 
> hash value not changing when mutated, or I can have the quality of 
> hashing by value, but I *cannot* have both.

So? You don't need the first.

> Thus, even if you make 
> lists hash by ID, I *still* need to have an immutable tuple type so that 
> I can get hash-by-value. 

No you don't. The same algorithm that works for hashing tuples will
work just as fine for hashing lists.

> Given that lists simply cannot replace every usage of tuples as 
> dictionary keys,

Yes they can. I wouldn't advise it but they can.

> the question becomes only one of which is more 
> important -- that lists compare to each other by value, or that lists 
> are usable as dictionary keys.  Given the ease of using compare-by-ID 
> class instances instead of lists, and the general usefulness of having 
> lists compare by value, I think that Python made the right choice.

And what choice would that be? Python has no problems with lists as
dictionary keys. Subclass list to provide a __hash__ method and the
result is a list that is usable as a dictionary key.

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


Re: Why are tuples immutable?

2004-12-22 Thread Bengt Richter
On 21 Dec 2004 10:37:20 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:

>Op 2004-12-18, Bengt Richter schreef <[EMAIL PROTECTED]>:
>>>
>>>As it turns out, python makes no difference in difficulty for making
>>>either mutable or immutable objects usable as dictionary keys. The
>>>only difference is that python only made its standard immutable
>>>types hashable and not its standard mutable objects.
>>>
>> In one sense a mutable could looked upon as immutable until it is mutated,
>> so why not allow its use in the same way as immutables?
>> Is that basically the point of view you are trying to explain?
>>
>> Ok, suppose you did allow that. What kind of error symptoms would you like
>> to have after a dict key is mutated and an attempt is made to look up the 
>> value
>> using a mutable equal to the original key value? Presumably a KeyError 
>> exception?
>> Or did you want to use a "frozen" copy of the original key, and not get a 
>> KeyError?
>> Or should a new value equal to the mutated current value of the original key 
>> succeed?
>
>Why should we expect certain error symptoms? If you have sorted mutable
>objects, mutated one element in the list and then apply an algorithm
>that depended on the list to be sorted; would you then expect a
>particular error symptom?
It depends on the use of the sorted list, but the subject I was discussing was 
your requirements
for a mutable-key dict. I was asking how you would like the mutable-key dict to 
behave
IF a key was mutated and an attempt was made to retrieve the origninally stored 
value
using a mutable key equal to the mutated value of the original key. E.g., if 
mkd is the mutable key dict,
 key = [0]
 mkd[key]=123
 key[0] = 1
 mkd[[1]] => ?

I said I would go with the assumption that you would like it to succeed (return 
the 123 above).
You said I assumed wrongly, but for some reason chose not to answer my 
questions or say what
a "correct" assumption would be. Ok. If you're not interested in pursuing the 
"correct" version
of the dict behavior _you_ were asking for, what are you interested in? ;-)

In the above, I am in a position to detect some "errors," depending what _your_ 
specs are.
I think it would be sloppy to let detectable errors pass silently, and in the 
case of mkd[[1]] above
clearly it will succeed or not, depending on design. The logical thing would 
seem to be to
return the matching value or design the dict so that mkd[[0]] would still 
retrieve 123 and
mkd[[1]] would raise a KeyError. Either way, this is a particular error symptom 
to expect, because
it is a direct consequence of a design decision. Your sorted list example does 
not say enough about
the designed usage to say what specific errors might be expected, so it's not 
directly comparable.

If you are saying you are happy with "undefined behavior" as the outcome of 
mutating keys, ok,
but if your implementation lets mutated-key errors pass silently, good luck 
debugging ;-)

>
>> Assuming the latter, what does this imply implementation-wise?
>
>You assume wrongly. I'm a bit sorry for that, because you obviously
>spend time in this.
That's ok, I made the choice ;-) I enjoy exploring ideas, and I thought it might
be useful to help you explore the consequences of what you seemed to be asking 
for,
and I was a bit curious how it would work out in practice when mutable keys 
were mutated.

I obviously could have made it work differently, and was trying to guess what 
alternative
you might be interested in. ISTM from the little experiment I posted in this 
thread that
mutable keys for dicts is fraught with pitfalls even if you intend never to 
mutate keys
in use, because of the potential for silent bugs if you accidentally do. But 
perhaps something
useful can be designed, if design decisions are carefully made.

If you enjoy exploring ideas too, you might get even more enjoyment by 
participating
more directly. E.g., at this point you might have volunteered to mention what 
would have
been a "correct" assumption to make in place of the one you say I made wrongly.

Your reticence does make me wonder what you consider to be rewarding about 
participating
in this kind of thread ;-) Cruel rejection is not the style of c.l.py, but if 
you have
had such experience, somewhere, bringing that baggage with you into the present 
in search
of resolution is likely to limit your new experiences to something less than an 
optimally
pleasant dialog ;-) The kids here mostly play nice ;-)

>
>> Hm, just for the heck of it, does this do what you want? (all features not 
>> tested, none tested beyond what you see,
>> and special methods like update and iterators will just work on the plain 
>> dict part if they work at all, unless
>> you add the code ;-)
>
>I don't expect anyting special. Python provides all that is needed. It
>is just that the documentation suggests otherwise.
>
So is there anything you would like to do to help make things better
for yourself and everyone? ;-)

Regards,
Bengt Richter
-- 
htt

Re: Why are tuples immutable?

2004-12-22 Thread Antoon Pardon
Op 2004-12-22, Fredrik Lundh schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:
>
>>> and to temporarily refer back to the top of this thread, do all this without
>>> any performance impact, compared to the current implementation.
>>>
>> Why should that be? This originated when someone argued that lists could
>> easily be resorted and reheapified.
>
> from the original post (by someone else):
>
> The way I see it is that if we enable __setitem__ for tuples there
> doesn't seem to be any performance penalty if the users don't use it
> (aka, python performance independent of tuple mutability).

The thread above (more than one '>')  was a tangents and this particular
tangent originated when someone wrote that my analogy with (the invariants of)
sorted lists and heaps was not a good one because they could be repaired easily.
So here we were talking about performace costs for a repair.

> to which you later added:
>
> The performace gained by using tuples as keys in dictionaries is
> entirely illusional.
>
> etc.  am I the only one one this list that can hold more than one post in my
> head and chew gum at the same time?

But this was another subthread. The argument here was about performance
gain because by having immutable keys, the dictionary wouldn't need to
make a copy when inserting a new key. The counter argument was that
it made more copying needed outside the dictionary code.


So you may be able to hold more than one post in your had, but you
seem unable to distinghuis the arguments in each.

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


Re: regular expression: perl ==> python

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

> 1) In perl:
> $line = "The food is under the bar in the barn.";
> if ( $line =~ /foo(.*)bar/ ) { print "got <$1>\n"; }
> 
> in python, I don't know how I can do this?
> How does one capture the $1? (I know it is \1 but it is still not clear
> how I can simply print it.
> thanks

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)

--
JZ ICQ:6712522
http://zabiello.om  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32 process name

2004-12-22 Thread Andrey Ivanov
[phil]

> I need to know if a process is running.
> not just python.exe
> but python.exe myapp

> from win32all
> EnumProcesses gives me the pids, then
> OpenProcess(pid) gives me a handle.
> Then what?
> GetModuleFileNameEX?

It   won't   do   the   right  thing  for  you.  As  far  as  I  know,
GetModuleFileNameEx()  returns  the name of a particular DLL, but what
you need to know is a *commandline*. I think that this is not possible
at  all.  Microsoft's  examples  use named mutexes to test whether the
process  is  already running or not. It is quite easy. Here's a quick
example:

import sys
import win32event

STANDARD_ACCESS_READ = 131072

mutex_handle = None

try:
mutex_handle = win32event.OpenMutex(STANDARD_ACCESS_READ, False, "Test")
except:
pass

if mutex_handle:
sys.exit("Instance is already running")
else:
mutex_handle = win32event.CreateMutex(None, False, "Test")

try:
while 1:
pass
except:
pass


-- 
Andrey

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


Re: regular expression: perl ==> python

2004-12-22 Thread Fredrik Lundh
"JZ" <[EMAIL PROTECTED]> 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

 



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


Re: Why are tuples immutable?

2004-12-22 Thread Fredrik Lundh
Antoon Pardon wrote:

> But this was another subthread.

oh, sorry, I was under the flawed assumption that the first few posts to a
thread should be seen in the context of the original post.  I guess I'm a bit
too old-fashioned for these new-fangled "let's change the subject for each
new post without changing the subject" thread thingies...

 



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


How to find unused methods

2004-12-22 Thread Martin Drautzburg
Is there an elegant way for finding unsent methods as in Smalltalk ? 

I am aware of the fact that due to pythons dynamic typing, no tool in
the world can find ALL unsent methods (same in Smalltalk). But finding
the most obvious ones would already be of some help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Garbage collector strategy

2004-12-22 Thread Martin Drautzburg
Just for curiosity: does python use a mark-and-sweep garbage collector
or simple reference counting? In the latter case it would not garbage
collect circular references, right ?

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?
-- 
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
Fredrik Lundh schrieb:

> Erik Geiger wrote:
> 
[...]
>> How to start a shell script without waiting for the exit of that shell
>> script? It shall start the shell script and immediately execute the next
>> python command.
> 
> if you have Python 2.4, you can use the subprocess module:
> 
> http://docs.python.org/lib/module-subprocess.html
> 
> see the spawn(P_NOWAIT) example for how to use it in your
> case:
> 
> http://docs.python.org/lib/node236.html

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
I don't understand the syntax of spawn os.spawnlp(os.P_NOWAIT, "/path/to
script", "the script again?", "the args for the script?")

> 
> as others have noted, os.spawn(P_NOWAIT) can be used directly, as
> can os.system("command&") (where the trailing "&" tells the shell to run
> the command in the background).

Thats what I've used in the Shellscript, but I haven't realized how to use
it in thy python script, thanks! :)

> 
> subprocess is available for Python 2.2 and 2.3 as well, by the way:
> 
> http://www.lysator.liu.se/~astrand/popen5/
> 
> 

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: how to start a new process while the other ist running on

2004-12-22 Thread Erik Geiger
Jean Brouwers schrieb:

> 
> 
> See the os. spawn* functions.  For example
> 
>   os.spawnv(os.P_NOWAIT, /path/to/script, args)
> 
> /Jean Brouwers
> 
> 
Thats what I've tried, but failed. 

Thanks anyway ;-)

Greets

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: how to start a new process while the other ist running on

2004-12-22 Thread Erik Geiger
Thanks, thats what I use now :)

Harlin Seritt schrieb:

> Quickie:
> 
> os.system("/path/to/script.sh &")
> 
> More elegant, have a look at threads
> 
> 
> Harlin Seritt
> 
> Erik Geiger wrote:
> 
>> Hi,
>> 
>> sorry, my english ist not that got but I'll try.
>> 
>> I have a running python script (capisuit incoming.py). This script shall
>> start a linux shell script. If I start this script like
>> os.system(/paht/to shellscipt.sh) the python scipt waits for the exit of
>> the shell script and then goes on with the rest of the python script.
>> 
>> How to start a shell script without waiting for the exit of that shell
>> script? It shall start the shell script and immediately execute the next
>> python command.
>> 
>> Thanks for any hints
>> 
>> 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


['ext.IsDOMString', 'ext.SplitQName']

2004-12-22 Thread Jindal, Pankaj
Hi,
I am new to Python-XML programming. I am using python 2.3.4, py2exe 0.5.3,
pyXML 0.8.4.
While making executable by py2exe  I am getting folowing warning:- The
following modules appear to be missing ['ext.IsDOMString', 'ext.SplitQName']
Even after trying the option:- setup.py py2exe --includes
xml.sax.drivers2.drv_pyexpat I am getting the same Warning.

 Please, can anybody help me out..
I will be highly obliged.
Thanks and regards
Pankaj Jindal



Aeroflex E-Newsletter 
Subscribe now to receive Aeroflex newsletters. As a subscriber,
you will receive all the latest Aeroflex and Racal Instruments
Wireless Solutions news including upcoming products, specials
and other Aeroflex related information.
Sign up now for our FREE monthly newsletter
http://www.aeroflex.com/aboutus/enewsletter/signup-form.cfm

This email and any attached files are confidential and intended
solely for the use of the individual/s or entity to whom it is
addressed. If you have received this email in error please notify:-
[EMAIL PROTECTED]

Racal Instruments Wireless Solutions Limited.
An AEROFLEX Company. Visit our website at:-
http://www.aeroflex.com/riws/

This footnote also confirms that this email message has
been swept for the presence of computer viruses.


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


Re: embedding: forcing an interpreter to end

2004-12-22 Thread Miki Tebeka
Hello pdectm,

> > You have a Python port to uClinux?
> 
> Nope, not yet.  That would have been my next post :-)  I thought there
> would have been much more work on cross-compiling and porting Python.
The problem is with Python's build proces, it 1'st created pgen and then
use it for the next stage.
This makes cross compilation very intersting :-)

> I may need to reconsider if Python is appropriate; the other
> possibiities are javascript or lua.
Lisp/Scheme?
(See http://tinyscheme.sourceforge.net/download.html for a very small
impelementation)

Bye.
--

Miki Tebeka <[EMAIL PROTECTED]>
http://tebeka.bizhat.com
The only difference between children and adults is the price of the toys
-- 
http://mail.python.org/mailman/listinfo/python-list


Python for Series 60 update

2004-12-22 Thread Ville Vainio
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 :-).

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Garbage collector strategy

2004-12-22 Thread Stephen Kellett
In message <[EMAIL PROTECTED]>, Martin Drautzburg 
<[EMAIL PROTECTED]> writes
Just for curiosity: does python use a mark-and-sweep garbage collector
or simple reference counting? In the latter case it would not garbage
collect circular references, right ?
gcmodule.c in the python sources shows the implementation, plus the code 
for this is well documented.

Stephen
--
Stephen Kellett
Object Media Limitedhttp://www.objmedia.demon.co.uk
RSI Information:http://www.objmedia.demon.co.uk/rsi.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Garbage collector strategy

2004-12-22 Thread Fredrik Lundh
Martin Drautzburg wrote:

> Just for curiosity: does python use a mark-and-sweep garbage collector
> or simple reference counting?

python the language doesn't specify this, but I assume you meant the CPython
interpreter.

both, sort of: it uses reference counting, and a separate "cycle breaking" 
collector
that runs when needed.  but unlike an ordinary m&s-collector, python's collector
looks for unreachable objects, not reachable 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?

nope.  instead, the allocator keeps track of container objects that support the 
GC
protocol.  non-containers, such as integers and strings, are not tracked.  for 
an
overview, see:

http://www.arctrix.com/nas/python/gc/

for the details, see Modules/gcmodule.c.

other implementations are free to use other GC strategies.  Jython, for 
example, uses
the Java GC to handle Jython garbage.

 



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


Re: Why are tuples immutable?

2004-12-22 Thread Antoon Pardon
Op 2004-12-22, Bengt Richter schreef <[EMAIL PROTECTED]>:
> On 21 Dec 2004 10:37:20 GMT, Antoon Pardon <[EMAIL PROTECTED]> wrote:
>
>>Op 2004-12-18, Bengt Richter schreef <[EMAIL PROTECTED]>:

As it turns out, python makes no difference in difficulty for making
either mutable or immutable objects usable as dictionary keys. The
only difference is that python only made its standard immutable
types hashable and not its standard mutable objects.

>>> In one sense a mutable could looked upon as immutable until it is mutated,
>>> so why not allow its use in the same way as immutables?
>>> Is that basically the point of view you are trying to explain?
>>>
>>> Ok, suppose you did allow that. What kind of error symptoms would you like
>>> to have after a dict key is mutated and an attempt is made to look up the 
>>> value
>>> using a mutable equal to the original key value? Presumably a KeyError 
>>> exception?
>>> Or did you want to use a "frozen" copy of the original key, and not get a 
>>> KeyError?
>>> Or should a new value equal to the mutated current value of the original 
>>> key succeed?
>>
>>Why should we expect certain error symptoms? If you have sorted mutable
>>objects, mutated one element in the list and then apply an algorithm
>>that depended on the list to be sorted; would you then expect a
>>particular error symptom?

> It depends on the use of the sorted list, but the subject I was discussing 
> was your requirements
> for a mutable-key dict. I was asking how you would like the mutable-key dict 
> to behave
> IF a key was mutated and an attempt was made to retrieve the origninally 
> stored value
> using a mutable key equal to the mutated value of the original key. E.g., if 
> mkd is the mutable key dict,
>  key = [0]
>  mkd[key]=123
>  key[0] = 1
>  mkd[[1]] => ?
>
> I said I would go with the assumption that you would like it to succeed 
> (return the 123 above).
> You said I assumed wrongly, but for some reason chose not to answer my 
> questions or say what
> a "correct" assumption would be. Ok. If you're not interested in pursuing the 
> "correct" version
> of the dict behavior _you_ were asking for, what are you interested in? ;-)

Well I think "like" is not the right word. Of course I would like that
it all magically repaired itself, but that is hardly a reasonable
expectation. To make it absolutly clear, I consider it a bug should
some code mutate a key in a dictionary (Under the provision that
the dictionary establishes a relationship between values, not
identities). I just find that countering such bugs by requiring keys to be
immutable is counterproductive. Sure advise people to use immutable keys
as much as possible. Caution people that should they use mutable keys
they should acertain themselves not to mutate such objects while they
are keys. But if a programmer finds that he needs a mutable object and
that it would be handy to use such an object as a key and he has some
assurance that those objects are stable while in use as a key, I see
nothing wrong with using such mutable objects as keys.

> In the above, I am in a position to detect some "errors," depending what 
> _your_ specs are.
> I think it would be sloppy to let detectable errors pass silently, and in the 
> case of mkd[[1]] above
> clearly it will succeed or not, depending on design. The logical thing would 
> seem to be to
> return the matching value or design the dict so that mkd[[0]] would still 
> retrieve 123 and
> mkd[[1]] would raise a KeyError. Either way, this is a particular error 
> symptom to expect, because
> it is a direct consequence of a design decision. Your sorted list example 
> does not say enough about
> the designed usage to say what specific errors might be expected, so it's not 
> directly comparable.

I don't know if it is so logical to expect those kind of things. You
have meddled with the internals of the dictionary and IMO that means
all bets are off.

> If you are saying you are happy with "undefined behavior" as the outcome of 
> mutating keys, ok,
> but if your implementation lets mutated-key errors pass silently, good luck 
> debugging ;-)

But that problem is not limited to dictionaries. If you make a heapqueue
and mutate an element in it, such errors will pass silently too and 
will be just as hard to debug. Or suppose you create a class that
keeps a sorted list of a number of objects and the programmer accidently
mutates an object in it. That will probably pass silently too and
give you night mares debugging.

The problem is also that you really can't make new immutable objects
AFAIK. I have once made a vector class that didn't have any mutating
method and I always used it as if it as immutable but because of
the "we are all consenting adults here" attitude of python I can't
assure that other people of my class won't directly change a vector.

Do you find I shouldn't use these vectors as keys?

>>> Assuming the latter, what does this imply implementation-wise?
>>
>>

Re: Why are tuples immutable?

2004-12-22 Thread Antoon Pardon
Op 2004-12-22, Fredrik Lundh schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:
>
>> But this was another subthread.
>
> oh, sorry, I was under the flawed assumption that the first few posts to a
> thread should be seen in the context of the original post.

So? In the mean time there have been more than 50 articles in this
thread. "First few" seems hardly still appropiate.

> I guess I'm a bit
> too old-fashioned for these new-fangled "let's change the subject for each
> new post without changing the subject" thread thingies...

Having a few subthreads after more than 50 articles hardly seems
to warrant the remark: "let's change the subject for each  new post
without changing the subject"

Those subthread had more in common with the original subject than
your remarks here and yet you didn't change the Subject header.

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


Threading Problem

2004-12-22 Thread Norbert
Hello *,
i am experimenting with threads and get puzzling results.
Consider the following example:
#
import threading, time

def threadfunction():
print "threadfunction: entered"
x = 10
while x < 40:
time.sleep(1) # time unit is seconds
print "threadfunction x=%d" % x
x += 10



print "start"
th = threading.Thread(target = threadfunction())
th.start()
print "start completed"
#
(the dots are inserted becaus Google mangles the lines otherwise)

This program gives the following result :

start
threadfunction: entered
threadfunction x=10
threadfunction x=20
threadfunction x=30
start completed

My aim was that the main program should continue to run while
threadfunction runs in parallel. That's the point of threads after all,
isn't it ?

I awaited something like the following :
start
threadfunction: entered
start completed<---
threadfunction x=10
threadfunction x=20
threadfunction x=30

Does anyone know what's going on here ?

Thanks for listening !

Norbert

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


Re: Python To Send Emails Via Outlook Express

2004-12-22 Thread ian
Hi Lenard,
Absolutely fantastic!!
That worked like a charm.
Now onto adapting it to send attachments.

Thanks again

Ian

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


Re: xmlrpclib question

2004-12-22 Thread writeson
Thanks for the responses, you were both on the right track, I just
didn't provide enough of the right information. I solved the problem by
changing "localhost" in the server code to actually contain the name of
the machine, the same as it appears in our DNS. This enabled the client
to connect to the server immediately. It's not clear in the example
code that this is necessary, but it makes sense that the server
wouldn't be able to 'listen' to anything on "localhost" other than same
machine applications because they would all use the lo interface.
Thanks!
Doug

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


Re: Threading Problem

2004-12-22 Thread Steve Holden
Norbert wrote:
Hello *,
i am experimenting with threads and get puzzling results.
Consider the following example:
#
import threading, time
def threadfunction():
.print "threadfunction: entered"
.x = 10
.while x < 40:
.time.sleep(1) # time unit is seconds
.print "threadfunction x=%d" % x
.x += 10

print "start"
th = threading.Thread(target = threadfunction())
th.start()
print "start completed"
#
(the dots are inserted becaus Google mangles the lines otherwise)
This program gives the following result :

start
threadfunction: entered
threadfunction x=10
threadfunction x=20
threadfunction x=30
start completed

My aim was that the main program should continue to run while
threadfunction runs in parallel. That's the point of threads after all,
isn't it ?
I awaited something like the following :
start
threadfunction: entered
start completed<---
threadfunction x=10
threadfunction x=20
threadfunction x=30
Does anyone know what's going on here ?
Well, I don't believe there's any guarantee that a thread will get run 
preference over its starter - they're both threads, after all. Try 
putting a sleep after th.start() and before the print statement and you 
should see that the "worker" thread runs while the main thread sleeps.

The same would be true if each were making OS calls and so on. When 
everything is more or les continuous computation, and so short it can be 
over in microseconds, there's no motivation for the scheduler to stop 
one thread and start another.

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: word to digit module

2004-12-22 Thread John Machin
Stephen Thorne wrote:
> On Wed, 22 Dec 2004 10:27:16 +0530, Gurpreet Sachdeva
> <[EMAIL PROTECTED]> wrote:
> > Is there any module available that converts word like 'one', 'two',
> > 'three' to corresponding digits 1, 2, 3??
>
> This seemed like an interesting problem! So I decided to solve it.
>
> I started with
> http://www.python.org/pycon/dc2004/papers/42/ex1-C/ which allowed me
> to create a nice test suite.
> import num2eng
> for i in range(4):
> e = num2eng.num2eng(i)
> if toNumber(e) != i:
> print e, i, toNumber(e)
>
> once this all important test suite was created I was able to knock up
> the following script. This is tested up to 'ninty nine thousand nine
> hundred and ninty nine'. It won't do 'one hundred thousand', and
isn't
> exceptionally agile. If I were to go any higher than 'one hundred
> thousand' I would probably pull out http://dparser.sf.net/ and write
a
> parser.
>

Parser?

The following appears to work, with appropriate dict entries for
'million', 'billion', etc:
[apologies in advance if @#$% groups-beta.google stuffs the indenting]
[apologies for the dots, which attempt to the defeat the
indent-stuffing]
.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)

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


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

2004-12-22 Thread Nick Coghlan
OK, I think I need to recap a bit before starting my reply (for my own benefit, 
even if nobody else's). (The rest of this post will also include a fair bit of 
repeating things that have already been said elsewhere in the thread)


The actual rule dictionaries use when deciding whether or not to allow a key is 
simply 'can I hash it?'. Lists don't provide a hash, and tuples only provide a 
hash if every item they contain provides a hash.

For the dictionary to behave sanely, two keys which compare equal must also hash 
equal. Otherwise, (key1 == key2) == (d[key1] is d[key2]) may not hold.

So the one absolute rule on hashes is that (x == y) must imply that (hash(x) == 
hash(y)). In other words, the hash operation must not involve any object 
properties that are not also involved in comparison for equality.

The rule recommended for hashes is that a mutable object only define a hash if 
both the comparison operation and the hash are based on immutable portions of 
the object (such as it's ID). (The language reference currently recommends 
something stricter - it suggests that you don't define hash at all if you define 
a custom comparison method on a mutable object. That's overly strict, though)

Now, and here's the key point: Python's builtin objects are written in 
accordance with this recommendation, which means the mutable objects like dict 
and list don't define __hash__ at all.

Antoon Pardon wrote:
that it would be handy to use such an object as a key and he has some
assurance that those objects are stable while in use as a key, I see
nothing wrong with using such mutable objects as keys.
Scarily enough, you're starting to persuade me that the idea isn't *completely* 
insane. Maybe merely mostly insane ;)

The interesting thing is that allowing mutable objects has keys doesn't require 
*any* changes to dict. It only requires changes to the mutable objects (e.g. 
having list adopt tuple's hash method).

Anyway, what are the consequences of a type which has a 'variable hash'?
The only real bad consequence is that the internal state of a dictionary can 
break if someone alters the hash of one of its keys. The restriction to 
'constant hashes' is aimed squarely at eliminating this class of programming 
errors. It doesn't actually provide any performance gain.

A performance loss would only occur if the dictionary tried to be helpful in 
detecting when a key mutates - and I see no reason why it should.

If you are saying you are happy with "undefined behavior" as the outcome of 
mutating keys, ok,
but if your implementation lets mutated-key errors pass silently, good luck 
debugging ;-)
But that problem is not limited to dictionaries. If you make a heapqueue
and mutate an element in it, such errors will pass silently too and 
will be just as hard to debug. Or suppose you create a class that
keeps a sorted list of a number of objects and the programmer accidently
mutates an object in it. That will probably pass silently too and
give you night mares debugging.
The longer I consider it, the more this seems like a valid analogy. There is 
nothing preventing dictionaries from having a rehash() method.

Consider:
# Mutate some value in mylist
mylist.sort()
# Mutate some key in mydict
mydict.rehash()
Rehash would work exactly as Antoon suggested - scan all the hash buckets, and 
any key which hashes incorrectly gets moved to the right place. Forgetting to 
rehash() would have consequences no worse than forgetting to sort().

The problem is also that you really can't make new immutable objects
AFAIK. I have once made a vector class that didn't have any mutating
method and I always used it as if it as immutable but because of
the "we are all consenting adults here" attitude of python I can't
assure that other people of my class won't directly change a vector.
Do you find I shouldn't use these vectors as keys?
This is a fair point, actually:
Py> from decimal import Decimal
Py> x = Decimal()
Py> hash(x)
0
Py> x._int = 1,
Py> hash(x)
1

But mutable objects is fraught with pitfall anyhow. Even mutating an
element in a list you are iterating over can give unexpected results
or just assigning a mutable to other names a few times and then mutating
it through one name and finding out an other name that was supposed to
stay stable, mutated too. Why else the warning against the use of
a default value of [] for an argument?
Another fair point, although I'm not sure that pointing out that mutable values 
already give you plenty of ways to shoot yourself in the foot is a point in 
*favour* of your idea :)

A last idea, but this definetly is only usefull for debugging, is
having a dictionary that keeps a copy of the key, with the ability
to check the keys againt the copy, this might help in debugging.
I have a different suggestion: an identity dictionary.
It ignores __hash__, __cmp__ and __eq__, and instead uses id() and is.
Or even something like:
override_dict(id, lambda x, y: x is y)()
Personnaly I find the atmosphere i

Re: Threading Problem

2004-12-22 Thread Alan Kennedy
[Norbert]
> i am experimenting with threads and get puzzling results.
> Consider the following example:
> #
> import threading, time
>
> def threadfunction():
> print "threadfunction: entered"
> x = 10
> while x < 40:
> time.sleep(1) # time unit is seconds
> print "threadfunction x=%d" % x
> x += 10
>
>
>
> print "start"
> th = threading.Thread(target = threadfunction())
The problem is here^^
You are *invoking* threadfunction, and passing its return value as the 
target, rather than passing the function itself as the target. That's 
why threadfunction's output appears in the output stream before the 
thread has even started.

Try this instead
#---
import threading, time
def threadfunction():
  print "threadfunction: entered"
  x = 10
  while x < 40:
time.sleep(1) # time unit is seconds
print "threadfunction x=%d" % x
x += 10
print "start"
th = threading.Thread(target = threadfunction)
th.start()
print "start completed"
#
Which should output the expected
>
start
threadfunction: entered
start completed
threadfunction x=10
threadfunction x=20
threadfunction x=30
regards,
--
alan kennedy
--
email alan:  http://xhaus.com/contact/alan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lazy argument evaluation (was Re: expression form of one-to-many dict?)

2004-12-22 Thread Nick Coghlan
Nick Coghlan wrote:
def lazycall(x, *args, **kwds):
  """Executes x(*args, **kwds)() when called"""
  return lambda : x(*args, **kwds)()
It occurred to me that this should be:
def lazycall(x, *args, **kwds):
   """Executes x()(*args, **kwds) when called"""
   return lambda : x()(*args, **kwds)
(Notice where the empty parens are)
Then this does the right thing:
lazycall(lazy(attrgetter('a'), x), y) # x.a(y)
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Threading Problem

2004-12-22 Thread Norbert
Thanks a lot, Steve, for your fast reply.
But the behaviour is the same if 'threadfunction' sleeps longer than
just 1 second. 'threadfunction' is of course a dummy to show the
problem, imagine a longrunning background-task.

If you are right, the question remains 'How can I assure that the
starting function finishes, while the other thread still runs ?' .  As
I said, this is the purpose of threading.

Thanks again
Norbert

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


Re: When was extended call syntax introduced?

2004-12-22 Thread Edward K. Ream
> > That was in Python 2.0, see

Thanks very much, Martin. 


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


Re: Threading Problem

2004-12-22 Thread Norbert
Thanks Alan,
i hoped it would be something trivial :)

Norbert

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


Re: Lazy argument evaluation (was Re: expression form of one-to-many dict?)

2004-12-22 Thread Nick Coghlan
Steven Bethard wrote:
There must be something wrong with this idea that I'm missing. . .

Well, it does cost you some conciceness, as your examples show[1]:
lazy(mul, x, y) v.s.   :x * y
lazy(itemgetter(i), x)  v.s.   :x[i]
lazy(attrgetter("a"), x)v.s.   :x.a
lazycall(lazy(attrgetter("a"), x))  v.s.   :x.a()
Not sure how I feel about this yet.  I don't personally need lazy 
argument evaluation often enough to be able to decide which syntax would 
really be clearer...
I think you've hit the downside on the head, though. Any time you have to use 
the operator module, you take a big hit in verbosity (particularly since noone 
ever came up with better names for attrgetter and itemgetter. . .)

There's a reason people like list comprehensions :)
Ah well, I'll let it bake for a while - I'm still not entirely sure about it 
myself, since I'm in a similar boat to you w.r.t. lazy evaluation (I usually 
just define functions that do what I want and pass them around).

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


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

2004-12-22 Thread Fredrik Lundh
Nick Coghlan wrote:

> I have a different suggestion: an identity dictionary.
>
> It ignores __hash__, __cmp__ and __eq__, and instead uses id() and is.

that's a rather common pattern, and you don't really need a special type
to handle it: just replace d[k] with d[id(k)].  if you really need to store the
keys in the dict, use d[id(k)] = k, v.

you can find some use of this pattern in Python's standard library.

 



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


Re: how to pass globals across modules (wxPython)

2004-12-22 Thread Jorge Luiz Godoy Filho
Fredrik Lundh, TerÃa 21 Dezembro 2004 16:33, wrote:

> well, in my applications, subsystems usually consists of one or more
> classes, or at least
> one or more functions.  code that needs the global context usually gets
> the content either as a constructor argument, or as an argument to
> individual methods/functions.

I see.  Differences in terminology.  We use the same approach as you do. 


Be seeing you,
Godoy.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threading Problem

2004-12-22 Thread Fredrik Lundh
Steve Holden wrote:

> Well, I don't believe there's any guarantee that a thread will get run 
> preference over its 
> starter - they're both threads, after all. Try putting a sleep after 
> th.start() and before the 
> print statement and you should see that the "worker" thread runs while the 
> main thread sleeps.

that's correct, but the "threading" module does a 0.01-second sleep
to get around this, no matter what thread scheduler you're using.

if you're building threads on top of the lower-level "thread" api, you have
to do that yourself.

 



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


Re: A rational proposal

2004-12-22 Thread Nick Coghlan
Mike Meyer wrote:
Well, you want to be able to add floats to rationals. The results
shouldn't be rational, for much the same reason as you don't want to
convert floats to rationals directly. I figure the only choice that
leaves is that the result be a float. That and float(rational) should
be the only times that a rational gets turned into a float.
Are you suggestiong that float(rational) should be a string, with the
number of degrees of precesion set by something like the Context type
in Decimal?
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.

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


Re: input record sepArator (equivalent of "$|" of perl)

2004-12-22 Thread Nick Coghlan
John Machin wrote:
Nick Coghlan wrote:
[snip]
delimeter.

Hey, Terry, another varmint over here!
Heh. Just don't get me started on the issues I have with typing apostrophes in 
the right spot. My *brain* knows where they go, but for some reason it refuses 
to let my fingers in on the secret. . .

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


mathmatical expressions evaluation

2004-12-22 Thread Tonino
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

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


Metaclasses

2004-12-22 Thread Bob . Cowdery
Title: Message



Hi
 
I am trying to build 
a capability based API. That is, an instance of the api will reflect the 
capabilities of some underlying services. I could have several different 
instances of the api concurrently running against different back end services. A 
ui applet will bind to an api instance. I want to make this easy to use from the 
ui perspective so I envisage exposing a number of properties as the variable 
part can be represented by properties. I want a property to exist only if a 
capability is available so it is easily tested. I have tried using Property and 
Metaclasses to do this and although both work I can't figure out how to make 
multiple different instances as both get executed on 'import' and thus only one 
instance can be created. Inside the metaclass I have to get hold of the 
capability map I want to build the instance against. The only way I can see to 
do this at the moment is to have a metaclass for each capability type and 
hardcode the type inside it, then pick the appropriate metaclass when I build 
the implementation class.
 
Regards
Bob
 
 
 
Bob Cowdery
CGI Senior Technical 
Architect
+44(0)1438 791517
Mobile: +44(0)7771 532138
[EMAIL PROTECTED]
 
 
 
*** Confidentiality Notice *** 
Proprietary/ConfidentialInformation belonging to CGI Group Inc. and its 
affiliatesmay be contained in this message. If you are not a 
recipientindicated or intended in this message (or responsible 
fordelivery of this message to such person), or you think forany reason 
that this message may have been addressed to youin error, you may not use or 
copy or deliver this messageto anyone else.  In such case, you should 
destroy thismessage and are asked to notify the sender by reply 
email.

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

Re: Is this a good use for lambda

2004-12-22 Thread Nick Coghlan
Jeff Shannon wrote:
Er, not as far as I can tell  the 2.4 feature was what wouldn't work 
consistently; the corrected version, using list() and reverse(), doesn't 
look like it has anything that'll be a problem in my 2.2 installation, 
and probably not in 2.1 
What he said :)
Although if you genuinely prefer a functional programming style, I'd go with 
Terry's answer rather than mine.

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

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


Re: How to find unused methods

2004-12-22 Thread TZOTZIOY
On 22 Dec 2004 10:27:58 +0100, rumours say that Martin Drautzburg
<[EMAIL PROTECTED]> might have written:

>Is there an elegant way for finding unsent methods as in Smalltalk ? 
>
>I am aware of the fact that due to pythons dynamic typing, no tool in
>the world can find ALL unsent methods (same in Smalltalk). But finding
>the most obvious ones would already be of some help.

If you don't mind *running* your program, profile it.  Or wrap all your
methods in call counting ones.  I think you will find lots of recipes
how to automagically do the latter, especially in the decorator section
of your favourite site :)
-- 
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best GUI for small-scale accounting app?

2004-12-22 Thread kdahlhaus
> ZOPE could provide the workaround but ZOPE seems really huge to
> me and an overkill for this. Or maybe it would work?

I am intenionally *not* trying to argue web vs traditional gui for your
app, but to tuck away for future apps, CherryPy2 is a lot easier than
Zope to use and programming it does not require much of a learning
curve.

Recently I did a simple app that started as wx Windows, got bogged
down, and switched to CherryPy/Cheetah running locally on the users
station.  I know more about wxWindows now than before, so perhaps
things would be different now, but at the time the gui was really
slowing my down my development.   I had a hard time getting my hands
around the wxWindows sizers.  They are simple in concept, but not easy
to learn at first in practice.

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.

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


Kamaelia Released

2004-12-22 Thread Michael Sparks
Hi,


I've already posted an announcement in comp.lang.python.announce
about this, but for those who were at Europython and remember me
giving a lightning talk on Kamaelia who don't read c.l.p.a - this
is just a quick note to say that we've been given the go ahead to
release it as open source and that it's now on sourceforge here:

   * http://kamaelia.sourceforge.net/

Essentially the bottom line idea is it's designed as a testbed
platform for building network servers, and specifically new
protocols. The reason for not using twisted is to try an alternate
approach is to see whether an alternate approach has any benefits.
(twisted is a better option if you just want something scalable
in python right now of course!)

The approach we've taken for concurrency is essentially lots of
small components communicating in CSP/Occam like manner. Each
component is a python generator, with extra attributes inboxes/outboxes
which act as queues/buffers. Interesting systems are then composed
by linking outboxes to inboxes allowing data to flow through the
system. 

For the moment the code is only available via anonymous CVS checkout,
but we'll probably start having nightly CVS snapshots at some point
soon.

Merry Christmas,


Michael.
-- 
[EMAIL PROTECTED]
British Broadcasting Corporation, Research and Development
Kingswood Warren, Surrey KT20 6NP

This message (and any attachments) may contain personal views
which are not the views of the BBC unless specifically stated.


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


Re: mathmatical expressions evaluation

2004-12-22 Thread beliavsky
There is QuantLib at http://quantlib.org/ . The site says "QuantLib is
written in C++ with a clean object model, and is then exported to
different languages such as Python, Ruby, and Scheme." I have not tried
it -- if it is easily usable from Python please write back to c.l.p.

There is a Python Finance email list at
http://www.reportlab.co.uk/mailman/listinfo/python-finance .

In calculations involving bonds one needs arrays to store payment dates
and amounts etc., for which numarray should be used instead of Python
lists, for efficiency.

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


Newbie namespace question

2004-12-22 Thread [EMAIL PROTECTED]
I have a variable that I want to make global across all modules, i.e. I
want it added to the builtin namespace.  Is there a way to do this?

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


Re: Newbie namespace question

2004-12-22 Thread deelan
[EMAIL PROTECTED] wrote:
I have a variable that I want to make global across all modules, i.e. I
want it added to the builtin namespace.  Is there a way to do this?
i would not pollute built-ins namespace.
how about:
### a.py
FOO = "I'm a global foo!"
### b.py
import a
print a.FOO
HTH,
deelan
--
@prefix foaf:  .
<#me> a foaf:Person ; foaf:nick "deelan" ;
foaf:weblog  .
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie namespace question

2004-12-22 Thread Steve Holden
[EMAIL PROTECTED] wrote:
I have a variable that I want to make global across all modules, i.e. I
want it added to the builtin namespace.  Is there a way to do this?
Of course: you can do *anything* in Python. I'm not sure this is to be 
recommended, but since you ask ... if you have

# mymod.py
print myname
then in some other module (and here specifically in the interactive 
interpreter) you can bind a value to "myname" in __builtins__ and it 
will be seen by mymod.py when it's imported:

 >>> __builtins__.myname = "MyValue"
 >>> myname
'MyValue'
 >>> import mymod
MyValue
 >>>
Having said all that, you have to be careful, since it's necessary to 
explicity assign to __builtins__.myname to change the value - if you 
just assign to myname then you create a new myname in the module's 
global namespace that will make the name in __builtins__ inaccessible.

So, what with that plus the way the names automagically appear it's 
probably something to relegate to the "definitely not best practice" 
category.

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: embedding: forcing an interpreter to end

2004-12-22 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
Well, the app is multi-threaded, so I do have a big issue getting
control back to my C program.  I just can not seem to cleanly stop the
interpreter.  The best I could do is:
void terminateInterpreter( PyInterpreterState *interp )
[...]
PyThreadState_SetAsyncExc(interp->tstate->thread_id, exc);
Py_DECREF(exc);
As I recall, there is a return value from SetAsyncExc()
which according to the documentation you *must* check
and handle appropriately if you want to avoid some
unspecified Bad Things from happening.
There was some recent (2-3 weeks ago?) discussion in the
newsgroup/mailing list about this as well, if you want
to check the archives.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: mathmatical expressions evaluation

2004-12-22 Thread aaronwmail-usenet
> have a task of evaluating a complex series (sorta) of mathematical
> expressions and getting an answer ...

If we assume that you are looking for functionality and speed is
secondary,
please have a look at the technique in


http://cvs.sourceforge.net/viewcvs.py/xsdb/xsdbXML/xsdbXMLpy/functions.py?view=markup

which uses the python parser to generate a parse tree for an arbitrary
expression and then imposes its own semantics on the tree.  In fact
take
a look at xsdb use guide under "Computing other derived values"

http://xsdb.sourceforge.net/guide.html

since xsdbXML implements general computations over xml inputs.
Let me know if you have any comments/questions/suggestions.
-- Aaron Watters

===
Later on we'll perspire, as we stare at the fire
And face so afraid, the bills left unpaid
Walking in a winter wonderland.  --stolen from "for better or worse"

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


Re: PyCon is coming - we need your help

2004-12-22 Thread jfj
I wish it was in Amsterdam.. ;)
Gerald
--
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression: perl ==> python

2004-12-22 Thread Doug Holton
Fredrik Lundh wrote:
"JZ" <[EMAIL PROTECTED]> 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
He was using the python interactive prompt, which I suspect you already 
knew.
--
http://mail.python.org/mailman/listinfo/python-list


Re: expression form of one-to-many dict?

2004-12-22 Thread Alex Martelli
Mike Meyer <[EMAIL PROTECTED]> wrote:

> > As in, say, calling
> > x = ternary(c, lambda:t, lambda:f)
> > ?  The 'lambda:' is a (not nice-looking, but...) "indication of
> > non-evaluation"... or am I misundertanding what you're saying?
> 
> No, you're saying it exactly right. And that does, indeed, do the
> trick. Just a bit ugly is all.

Yeah, there's a PEP to provide alternate, less-ugly syntax sugar for
this specific use of lambda, but I don't think it stands any chance of
passing.


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


Re: Printing

2004-12-22 Thread Peter Hansen
Craig Ringer wrote:
I don't have a windows box to test with - well, our NT4 server, but it
doesn't have anything on the serial ports. I would think that one just:
printerport = open("lpt1","w")
but on my NT box that results in a file not found exception. lpt0 opens,
but I have no idea if it works. I did a quick google search and turned
up little, but I'm sure this has been asked before so you might want to
try a google groups search, etc.
The above works, provided you have configured the printer
to be addressable that way.  Note that you might well want
to use binary mode ("wb") to avoid newline-mangling.
Python can open "lpt0", but that just creates a file with
that name in your current directory... there is no such
printer port.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie namespace question

2004-12-22 Thread [EMAIL PROTECTED]
Here's my situation, I've created some scripts to configure WebSphere
and the WAS scripting engine assigns the variable AdminConfig to a Java
object.  I have created classes that wrap the AdminConfig settings,
simplifying the interface for those who want to script their server
installs.

At the command line, I pass the main script in and AdminConfig is
automatically assigned and placed in the global namespace and control
is passed to the main script.

Therefore...

#configure_server_foo.py
from jdbc import DataSource

print globals()["AdminConfig"]  # Will print com.ibm.yada.yada.yada

# Create a couple of data sources
ds = DataSource("ServerName")
ds.create("dsname1", "connectionInfo", "etc")
ds.create("dsname2", "connectionInfo", "etc")

Now, in jdbc.py I have

#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')

Run it and get a name error, which, makes sense.
If I try to use the standard import solution as deelan suggests I have
a circular reference on the imports and I get an error that it can't
import class DataSource (presumbably because it hasn't gotten far
enough through jdbc.py to realize that there's a DataSource class
defined.

Any insight would be greatly appreciated, and thanks to both deelan and
Steve for your help.

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


Ack! Zombie processes won't die!

2004-12-22 Thread Brian
>From one script, I'm spawnv'ing another that will launch mpg123 to play a 
specified mp3.  Problem is that After the second script has launched 
mpg123, it'll turn into a zombie process.  It doesn't happen when I launch 
it from the command line, so there's something wrong with the way I'm 
calling it (I believe).

mp3pid = os.spawnv(os.P_NOWAIT, "/oter/playfile.py", ["playfile", filename, 
"0"])

Shouldn't this launch the script without waiting for it to finish?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression: perl ==> python

2004-12-22 Thread JZ
Dnia Wed, 22 Dec 2004 10:27:39 +0100, Fredrik Lundh napisał(a):

>> 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.

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


Re: Ack! Zombie processes won't die!

2004-12-22 Thread Jp Calderone


On Wed, 22 Dec 2004 15:37:18 GMT, Brian <[EMAIL PROTECTED]> wrote:
>>From one script, I'm spawnv'ing another that will launch mpg123 to play a 
> specified mp3.  Problem is that After the second script has launched 
> mpg123, it'll turn into a zombie process.  It doesn't happen when I launch 
> it from the command line, so there's something wrong with the way I'm 
> calling it (I believe).
> 
> mp3pid = os.spawnv(os.P_NOWAIT, "/oter/playfile.py", ["playfile", filename, 
> "0"])
> 
> Shouldn't this launch the script without waiting for it to finish?

  Yes.  But since you told it not to wait on the child process, you 
are now responsible for waiting on it.  Child processes are zombies 
until their parent "reaps" them.  This is done with the wait() 
function:

pid, status = os.wait()

  or the waitpid() function:

pid, status = os.waitpid(mp3pid, options)

  Of course, both of these block.  When a child process exits, the parent 
receives SIGCHLD.  You could install a signal handler for this and only 
call os.wait/pid() then.  Of course, signal delivery is unreliable, so 
this could still leave you with zombie processes.  You could use 
os.waitpid() with the WNOHANG option to prevent it from blocking and call 
it periodically.  This would leave you with a zombie for a short while, but
then clean it up.  You could combine signal handling and polling to completely 
minimize the time the zombie exists.

  You could also use something other than os.spawnv().  The new subprocess 
module may have something that simplifies this (I haven't looked at it in 
detail yet).  Twisted's spawnProcess() might also be worth a look, as it 
does take care of waiting at the appropriate time.

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


Peter Hansen [Re: newbie question]

2004-12-22 Thread Doug Holton
Peter Hansen wrote:
Luis M. Gonzalez wrote:
As far as I could see, everythime the word "boo" is typed, some sort of
censorship or plain bashing comes up, and I think this is not fair.
I think doing this by defending Doug's postings, however, might weaken
the strength of your position just a little. (Okay, I mean "a lot".)
Flame away, Peter.
As a result of all the activity in the "Boo who?" thread, however,
that you started
I went and searched a bit to find out who this Doug character is.
It turns out that he's been mentioning Boo in postings *to newbies*
repeatedly over the last few months.  These are people trying
to use Python, having a question or difficulty about it, and he
launches into a sales job about some other language.
Actually, it was only in the context of someone asking about a feature 
python does not have (such as enums, or static typing declarationg, or 
anonymous methods) and will likely not have for some time.  I I have no 
financial connection to boo or python.  If you want to call me an 
evangelist for boo, then you must also call me an evangelist for python, 
as well as pretty much everyone here.  In fact though, you only mean the 
term "evangelist" as yet another disprectful flame.

If only I had taken the time to research your background before choosing 
to take your posts seriously.  Since you have spent such great effort in 
misrepresenting my views and spreading your vitriol, here is some 
background on you:
The very first hit for Peter Hansen:
http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/df3207f58d429a2d/4789c8134d78c77a?q=Peter+Hansen&_done=%2Fgroup%2Fcomp.lang.python%2Fsearch%3Fgroup%3Dcomp.lang.python%26q%3DPeter+Hansen%26qt_g%3D1%26searchnow%3DSearch+this+group%26&_doneTitle=Back+to+Search&&d#4789c8134d78c77a
even recently:
http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/16590f4138b6a978/75c05b3f81bb3a34?q=%22NO+REALLY%22+Hansen&_done=%2Fgroup%2Fcomp.lang.python%2Fsearch%3Fgroup%3Dcomp.lang.python%26q%3D%22NO+REALLY%22+Hansen%26qt_g%3D1%26searchnow%3DSearch+this+group%26&_doneTitle=Back+to+Search&&d#75c05b3f81bb3a34
and of course the flame thread he started:
http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/35ce883c8b04d181/ab172cb34bdc0891?q=Peter+Hansen&_done=%2Fgroup%2Fcomp.lang.python%2Fsearch%3Fq%3DPeter+Hansen%26start%3D10%26&_doneTitle=Back+to+Search&&d#ab172cb34bdc0891
--
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression: perl ==> python

2004-12-22 Thread Jp Calderone
On Wed, 22 Dec 2004 16:44:46 +0100, JZ <[EMAIL PROTECTED]> wrote:
>Dnia Wed, 22 Dec 2004 10:27:39 +0100, Fredrik Lundh napisał(a):
> 
> >> 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.

  Note that _ is only automagically defined when you are using the 
interpreter interactively.  If you were to run this program on the 
command line, or invoke it any way other than interactively, it
breaks in the way Fred demonstrated.  You should avoid using _ 
in programs.  It is a convenience for interactive use only.

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


Re: regular expression: perl ==> python

2004-12-22 Thread Fredrik Lundh
"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:

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 /.../"

the "_" symbol has no special meaning when you run a Python program, so the
"if re.search" construct won't work.

 



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


Re: newbie question

2004-12-22 Thread Stephen Waterbury
Luis M. Gonzalez wrote:
Amyway, I wouldn't want to use this list to talk about Boo, because I
think that the best place to do it is comp.lang.boo.
However, since I think it is definetely python related (I know you
disagree, but others don't) I see no harm in mentioning it here
occasionally.
Luis, that is *exactly* Peter's position:
Peter Hansen wrote:
... If Doug wants to come in from time to time and mention Boo,
however, he's welcome to do so.  ...
... so there is no need for you to say you see no harm in it,
making it sound as though Peter *does* see harm in it.
Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie namespace question

2004-12-22 Thread Brandon
And I just realized that Jython doesn't support the __builtins__
variable...  :(

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


Re: Newbie namespace question

2004-12-22 Thread Peter Hansen
Steve Holden wrote:
then in some other module (and here specifically in the interactive 
interpreter) you can bind a value to "myname" in __builtins__ and it 
will be seen by mymod.py when it's imported:

 >>> __builtins__.myname = "MyValue"
Steve's basic premise is correct, but he's chosen the wrong
name to use.  As Fredrik Lundh has written here 
http://mail.python.org/pipermail/python-list/2002-June/109090.html
the name above is an implementation detail and one should
always do this instead:

import __builtin__
__builtin__.myname = "MyValue"
And doing so reinforces the idea that this is Almost Always
a Bad Idea.  :-)
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Threading Problem

2004-12-22 Thread Ishwor
On Wed, 22 Dec 2004 12:55:46 +, Alan Kennedy <[EMAIL PROTECTED]> wrote:
> [Norbert]
> > i am experimenting with threads and get puzzling results.
> > Consider the following example:
> > #
> > import threading, time
> >
> > def threadfunction():
> > print "threadfunction: entered"
> > x = 10
> > while x < 40:
> > time.sleep(1) # time unit is seconds
> > print "threadfunction x=%d" % x
> > x += 10
> >
> >
> >
> > print "start"
> > th = threading.Thread(target = threadfunction())
> 
> The problem is here^^
> 
> You are *invoking* threadfunction, and passing its return value as the
> target, rather than passing the function itself as the target. That's
> why threadfunction's output appears in the output stream before the
> thread has even started.
> 
> Try this instead
> 
> #---
> 
> import threading, time
> 
> def threadfunction():
>   print "threadfunction: entered"
>   x = 10
>   while x < 40:
> time.sleep(1) # time unit is seconds
> print "threadfunction x=%d" % x
> x += 10
> 
> print "start"
> th = threading.Thread(target = threadfunction)
> th.start()
> print "start completed"
> 
> #
> 
> Which should output the expected
> 
> >
> start
> threadfunction: entered
> start completed
> threadfunction x=10
> threadfunction x=20
> threadfunction x=30
> 
> regards,
> 
> --
> alan kennedy
> --
> email alan:  http://xhaus.com/contact/alan

nice chum ;) liked the way you explained. Clear and easy to
understand.. why doesn't the keyboardInterrupt seem to work? I am
working in IDLE and it doesn't seem to stop the thread ???!!??
output of above code in IDLE shell:

threadfunction x=75

KeyboardInterrupt
>>> 
threadfunction x=80



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


Re: regular expression: perl ==> python

2004-12-22 Thread JZ
Dnia Wed, 22 Dec 2004 16:55:55 +0100, Fredrik Lundh napisał(a):

> the "_" symbol has no special meaning when you run a Python program, 

That's right. So the final code will be:

import re
line = "The food is under the bar in the barn."
found = re.search('foo(.*)bar',line)
if found:  print 'got %s\n' % found.group(1)

-- 
JZ ICQ:6712522
http://zabiello.com  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie namespace question

2004-12-22 Thread Brandon
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!

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


Re: mod_python and xml.sax

2004-12-22 Thread Jeffrey Froman
Fredrik Lundh wrote:

> iirc, both apache and python uses the expat parser; if you don't make sure
> that both use the same expat version, you may get into trouble.

Thank you very much Fredrik, this does seem to be the problem I was having.

> this 
> poster claims to have a fix:
> 
> http://www.modpython.org/pipermail/mod_python/2004-May/015569.html

In fact two fixes are offered in this one short post :-) The second fix,
linking Python against the system Expat library, is specifically warned
against in Modules/Setup:

"""
#... Source of Expat 1.95.2 is included in
# Modules/expat/.  Usage of a system shared libexpat.so/expat.dll is
# not advised.
"""

So I went with the first fix -- I upgraded the system library to Expat
1.95.8 to match the Expat bundled with Python 2.4 (the excerpt above is
apparently a little outdated). Everything is now working again.

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


Re: What is on-topic for the python list [was "Re: BASIC vs Python"]

2004-12-22 Thread Stephen Waterbury
Erik Max Francis wrote:
Doug Holton wrote:
I'm not going to dignify that or the rest of your note with a response.
Please stop dignifying the whole group, then.
Amen!
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyCon is coming - we need your help

2004-12-22 Thread Aahz
In article <[EMAIL PROTECTED]>,
jfj  <[EMAIL PROTECTED]> wrote:
>
>I wish it was in Amsterdam.. ;)

Feel free to run one there!  Then again, there's already EuroPython.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"19. A language that doesn't affect the way you think about programming,
is not worth knowing."  --Alan Perlis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question

2004-12-22 Thread Doug Holton
Stephen Waterbury wrote:
Luis M. Gonzalez wrote:
Amyway, I wouldn't want to use this list to talk about Boo, because I
think that the best place to do it is comp.lang.boo.
However, since I think it is definetely python related (I know you
disagree, but others don't) I see no harm in mentioning it here
occasionally.

Luis, that is *exactly* Peter's position:
Peter Hansen wrote:
... If Doug wants to come in from time to time and mention Boo,
however, he's welcome to do so.  ...

... so there is no need for you to say you see no harm in it,
making it sound as though Peter *does* see harm in it.
You can defend Peter all you want, but you can't take back the other 
things he has said which you did not cite.

Quote:
"I think doing this by defending Doug's postings, however, might weaken
the strength of your position just a little. (Okay, I mean "a lot".) "
A flame.
Quote:
"About the only time the word "boo" _does_ come up, it comes up
in one of Doug's posts, often in an apparent attempt to "help"
a Python newbie by pointing him in a misleading manner"
A misrepresentation of my intentions.  If someone asks if python has 
interfaces, and I say first, pyprotocols has something similar, but boo 
does have support for real interfaces, then that is "help" and that is 
not misleading in the slightest.

Quote:
"As a result of all the activity in the "Boo who?" thread, however, "
He failed to mention that he is the one who started and propagated this 
very thread, which devolved into nothing more than a flame-fest, which 
was his intention all along.

Quote:
"I went and searched a bit to find out who this Doug character is. "
Another flame, and we are still in the same note by Peter Hansen, folks.
Quote:
"It turns out that he's been mentioning Boo in postings *to newbies*
repeatedly over the last few months."
*to newbies* - oh my god, dare I mention the word boo to a newbie. 
Another mischaracterization of what I did.

Quote:
"These are people trying
to use Python, having a question or difficulty about it, and he
launches into a sales job about some other language. "
I am not selling anything.  This is a subtle flame related to calling me 
an "evangelist".  Does Peter Hansen make money using python?  Does he 
have something to sell at engcorp that uses CPython?

Quote:
"Would you defend someone who came into this group and responded
(admittedly helpfully, sometimes, in other ways) to newbie
questions by constantly saying "you can do this much more easily
in Perl of course, see www.perl.codehaus.org"? "
Another complete mischaracterization of what I did.  When someone asks 
for something that they cannot do in python, then I noted alternative 
solutions, such as jython or boo or whatever tool is best for the job.

Quote:
"Then downright offensive."
Another flame.
Quote:
"What Doug has been doing is like standing at the door of
a mission run by a church a..."
Yet again, another flame.
Quote:
"he turns on them and accuses them
of religious persecution, and being unfriendly to boot. "
Another mischaracterization.  In fact, a complete lie.
I'm only halfway through his message.  It would take me all day to point 
out all his flames.
--
http://mail.python.org/mailman/listinfo/python-list


Re: File locking is impossible in Windows?

2004-12-22 Thread elbertlev
I just have written the program in "C", which does the same. It behaves
almost the way you described.

Tthe copy command gives such diagnostic:

The process cannot access the file because
another process has locked a portion of the file.
0 file(s) copied.

BUT THE FILE IS ACTUALLY OVERWRITTEN..

I'm posting this question on MS newsgroup
microsoft.public.win32.programmer.kernel

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


Re: Newbie namespace question

2004-12-22 Thread deelan
[EMAIL PROTECTED] wrote:
(...)
Run it and get a name error, which, makes sense.
If I try to use the standard import solution as deelan suggests I have
a circular reference on the imports and I get an error that it can't
import class DataSource (presumbably because it hasn't gotten far
enough through jdbc.py to realize that there's a DataSource class
defined.
oh, i see. so the scenario is more complex.
Any insight would be greatly appreciated, and thanks to both deelan and
Steve for your help.
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.
bye.
--
@prefix foaf:  .
<#me> a foaf:Person ; foaf:nick "deelan" ;
foaf:weblog  .
--
http://mail.python.org/mailman/listinfo/python-list


trouble building python2.4

2004-12-22 Thread Matthew Thorley
Greetings, I just downloaded the python2.4 source from python.org and 
built it the usual way, i.e. ./configure && make. What I don't 
understand is that the resulting binary, when run, prints this line 
Python 2.3.4 (#1, Nov 15 2004, 10:29:48) at the top of its banner. 
Further more, the poplib modules complains when I try to call the 
poplib.POP3_SSL class, saying that the module has no such class, though 
the online docs say it does.

I read the README and I didn't see anything about having to pass options 
to configure to get it to build version 2.4. I appears to me that the 
tarball I downloaded wasn't really python2.4, even though it was 
'official' and named Python-2.4.tgz.

Can anyone please tell me what might of happened, or if they have had a 
similar experience?

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


Re: [Re: newbie question]

2004-12-22 Thread Reinhold Birkenfeld
Doug Holton wrote:
> Peter Hansen wrote:
>> Luis M. Gonzalez wrote:
>> 
>>> As far as I could see, everythime the word "boo" is typed, some sort of
>>> censorship or plain bashing comes up, and I think this is not fair.
>>
>> I think doing this by defending Doug's postings, however, might weaken
>> the strength of your position just a little. (Okay, I mean "a lot".)
> 
> Flame away, Peter.
> 
>> As a result of all the activity in the "Boo who?" thread, however,
> 
> that you started

Apart from that it is considered disrespectful to put your "opponent's"
name into the subject, this flame war is biting its tail already.

Reinhold

-- 
[Windows ist wie] die Bahn: Man muss sich um nichts kuemmern, zahlt fuer
jede Kleinigkeit einen Aufpreis, der Service ist mies, Fremde koennen
jederzeit einsteigen, es ist unflexibel und zu allen anderen Verkehrs-
mitteln inkompatibel.   -- Florian Diesch in dcoulm
-- 
http://mail.python.org/mailman/listinfo/python-list


logging from severl classes

2004-12-22 Thread flupke
Hi,
i'm trying to log to the same file (using logging module) from different 
classes but i can't seem to get it to work.
File 1 is the main file which sets up the logger and then i want to also
use the same logger in another class
This is what i have

file1
=
import logging
class A:
   def __init__(self):
self.logger = logging.getLogger("app_logfile")
### stdout handler ###
self.logger.setLevel(logging.DEBUG)
stream_hld = logging.StreamHandler()
stream_hld.setLevel(logging.DEBUG)
stream_formatter =
		logging.Formatter('%(asctime)s %(levelname)s %(module)s 			%(lineno)d 
%(message)s ')
stream_hld.setFormatter(stream_formatter)
self.logger.addHandler(stream_hld)")
=

file2
=
import logging
class B:
   def __init__(self):
self.logger = logging.getLogger("app_logfile")
self.logger.debug("creating class B")
   def otherfunction(self):
self.logger.debug("in otherfunction")
=
But i get an error:
  AttributeError: B instance has no attribute 'logger'
I was hoping that by requesting a logger with the same name 
(app_logfile) i would get the setup also and could use the logger 
straight away. Funny thing is that the use of the logger in the __init__ 
function of class B works but the call to the logger in otherfunction 
doesn't work and results in the error above.
Class B is created after class A so the logger object exists already.

Any ideas of what i'm doing wrong and how i can achieve setting up the 
logger object only once?

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


MIDI (was - Re: BASIC vs Python)

2004-12-22 Thread Bob van der Poel
Jan Dries wrote:
Andrew Dalke wrote:
Jan Dries
If you just want to play notes, you could look at MIDI.

[snip]
It's hard to compare that to the current era.  Sound
clips are much more common, it's easy to record audio,
keyboards and other specialized devices are cheap, and
there's plenty of mixer and recording software.  Were
I to have started now I would have taken a different
course and perhaps one of these newer things would have
interested me more.

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. And the 
MIDI file format was created in those days, on Atari. The Atari also had 
a Yamaha YM2149 sound chip on it that one could mess with in the way you 
describe, and I did play with that too. But the cool thing about MIDI 
was that it came with additional stuff, such as multiple voices, and 
different timbres for different instruments. And I didn't have to bother 
with the attack-decay-sustain-release envelope in order to make my notes 
sound like notes instead of beeps. Playing with the sound chip was like 
assembler, while playing with MIDI was more like a higher level 
language. At the time I was a teenager and couldn't afford my own 
keyboard though, and the Atari didn't have a sufficiently sophisticated 
audio system for playback of MIDI files.

Back in 1995 my then girlfriend wrote a thesis on AI where she did an 
analysis of Rachmaninov's Ampico rolls in an attemt to try to extract 
characteristics from that that could be applied to any piece of music to 
make it sound more "human" than when played by a computer.
I helped her out by writing a "notes to MIDI" converter, to make the 
results of her work audible.
I seem to remember that even then we still had to rely on a keyboard or 
so to do the playback.

But nowadays even the cheapest PC comes with "multi-media" sound 
hardware, and playback of MIDI files is easy. And the nice thing for me 
to find out is that the good old file format from back in the days on 
Atari is still out there, and well supported by programs like Windows 
Media Player.
Frankly I share your sentiment and "these newer things" like sound 
clips, mixers, recording software and so have never managed to 
interested me either. But MIDI is not among those, at least not for me. 
Because of my particular background, MIDI has for about 20 years now 
been the "serious" way to playing notes. And in fact, to the best of my 
knowledge it is still the easiest way to get decent notes out of my PC. 
A while ago I bought a few software packages that enable one to enter 
notes and play them back. After trying out half a dozen of these, I 
ended rolling my own solution in just 400 lines of Python, plus a Python 
module to read/write MIDI files.

Regards,
Jan
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.

--
Bob van der Poel ** Wynndel, British Columbia, CANADA **
EMAIL: [EMAIL PROTECTED]
WWW:   http://mypage.uniserve.com/~bvdp
--
http://mail.python.org/mailman/listinfo/python-list


Re: Step by step: Compiling extensions with MS Visual C++ Toolkit 2003 - msvccompiler-patch.txt (0/1)

2004-12-22 Thread wjb131
...
> d:\Python24\include\pyconfig.h(30) : fatal error C1083: Cannot open
> include file
> : 'io.h': No such file or directory
> error: command '"D:\Programme\Microsoft Visual C++ Toolkit
> 2003\bin\cl.exe"' fai
> led with exit status 2
>
> why?

Under :
HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio
\7.1\VC\VC_OBJECTS_PLATFORM_INFO\Win32\Directories

You need to add the strings:
"Include Dirs"(path to toolkit \include; path to platform sdk \include)
"Library Dirs"(path to toolkit \lib; path to platform sdk \lib)
"Path Dirs" (path to toolkit \bin; path to platform sdk \bin)

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


Re: trouble building python2.4

2004-12-22 Thread Erik Max Francis
Matthew Thorley wrote:
Greetings, I just downloaded the python2.4 source from python.org and 
built it the usual way, i.e. ./configure && make. What I don't 
understand is that the resulting binary, when run, prints this line 
Python 2.3.4 (#1, Nov 15 2004, 10:29:48) at the top of its banner. 
Further more, the poplib modules complains when I try to call the 
poplib.POP3_SSL class, saying that the module has no such class, though 
the online docs say it does.
You've got a copy of Python 2.3.4 installed on your system which is in 
your PATH first.

--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
  And your daddy died for you / And I'll do the same
  -- India Arie
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Re: newbie question]

2004-12-22 Thread Doug Holton
Reinhold Birkenfeld wrote:
Doug Holton wrote:
Peter Hansen wrote:
As a result of all the activity in the "Boo who?" thread, however,
that you started

Apart from that it is considered disrespectful to put your "opponent's"
name into the subject, this flame war is biting its tail already.
So putting "Boo Who?" in the subject is not disrespectful?  You have 
just proven my point that Peter Hansen created that thread for no 
purpose but to troll and flame.
--
http://mail.python.org/mailman/listinfo/python-list


Re: trouble building python2.4

2004-12-22 Thread Matthew Thorley
Erik Max Francis wrote:
Matthew Thorley wrote:
Greetings, I just downloaded the python2.4 source from python.org and 
built it the usual way, i.e. ./configure && make. What I don't 
understand is that the resulting binary, when run, prints this line 
Python 2.3.4 (#1, Nov 15 2004, 10:29:48) at the top of its banner. 
Further more, the poplib modules complains when I try to call the 
poplib.POP3_SSL class, saying that the module has no such class, 
though the online docs say it does.

You've got a copy of Python 2.3.4 installed on your system which is in 
your PATH first.

I have got to be the stupidest person on the face of the planet. Thanks 
very much. I was in the Python-2.4 dir, but I didn't call python with 
./python. I can't believe I missed that.

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


Re: [Re: newbie question]

2004-12-22 Thread Ed Leafe
On Dec 22, 2004, at 11:38 AM, Reinhold Birkenfeld wrote:
Apart from that it is considered disrespectful to put your "opponent's"
name into the subject, this flame war is biting its tail already.
	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?

 ___/
/
   __/
  /
 /
 Ed Leafe
 http://leafe.com/
 http://dabodev.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question

2004-12-22 Thread Richie Hindle

[Doug]
> I'm only halfway through his message.  It would take me all day to point 
> out all [Peter Hansen's] flames.

Doug, this is not worth your time.  It certainly isn't worth mine, nor
that of the other thousands of people who are being subjected to this
argument.  Please, consider putting your energies into something more
positive, either here or elsewhere.

Peter, Fredrik: Please consider giving up the argument.  Hopefully Doug
will either lighten up and return to contributing usefully, or give up and
go away.  (For what it's worth, I'd rather it was the former.)

the-last-haven-of-civilisation-on-the-net-is-under-threat-ly yrs,

-- 
Richie Hindle
[EMAIL PROTECTED]

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


Re: Ack! Zombie processes won't die!

2004-12-22 Thread Keith Dart
Brian wrote:
From one script, I'm spawnv'ing another that will launch mpg123 to play a 
specified mp3.  Problem is that After the second script has launched 
mpg123, it'll turn into a zombie process.  It doesn't happen when I launch 
it from the command line, so there's something wrong with the way I'm 
calling it (I believe).

mp3pid = os.spawnv(os.P_NOWAIT, "/oter/playfile.py", ["playfile", filename, 
"0"])

Shouldn't this launch the script without waiting for it to finish?
It does, but the OS keeps the process information around until you 
"wait" on it, with "reaps", or collects the exit status then. You can do 
this asyncronously with a SIGCHLD handler. However, this has already 
been done.

In the the pyNMS package on sourceforge 
(http://sourceforge.net/projects/pynms) there is a module called 
"proctools". It has a process manager that does this for you.

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


Re: [Re: newbie question]

2004-12-22 Thread Steve Holden
Doug Holton wrote:
Reinhold Birkenfeld wrote:
Doug Holton wrote:
Peter Hansen wrote:
As a result of all the activity in the "Boo who?" thread, however,

that you started

Apart from that it is considered disrespectful to put your "opponent's"
name into the subject, this flame war is biting its tail already.

So putting "Boo Who?" in the subject is not disrespectful?  You have 
just proven my point that Peter Hansen created that thread for no 
purpose but to troll and flame.
Good grief, man, get a life. This is Usenet, not the United Nations.
it's-only-ones-and-zeroes-ly y'rs  - 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: Metaclasses

2004-12-22 Thread Robert Brewer
Bob Cowdery 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. I could have several
> different instances of the api concurrently running
> against different back end services. A ui applet will
> bind to an api instance. I want to make this easy to
> use from the ui perspective so I envisage exposing a
> number of properties as the variable part can be
> represented by properties. I want a property to exist
> only if a capability is available so it is easily tested.
> I have tried using Property and Metaclasses to do this
> and although both work I can't figure out how to make
> multiple different instances as both get executed on
> 'import' and thus only one instance can be created.
> Inside the metaclass I have to get hold of the capability
> map I want to build the instance against. The only way I
> can see to do this at the moment is to have a metaclass
> for each capability type and hardcode the type inside it,
> then pick the appropriate metaclass when I build the
> implementation class.
 
I was with you until the last couple of sentences. :) I *think* you're trying 
to write something like this:

class MetaAPI(type):
def __init__(cls, name, bases, dct):
for name, method in capabilities.iteritems():
setattr(cls, name, method)

class API(object):
__metaclass__ = MetaAPI

...where all capable behaviors are attached to the API _class_.

But then you start talking about "instances", and I'm not sure whether you mean 
instances of the API class or not, because the metaclass doesn't have much to 
do with that. If you want to conditionally attach methods to instances of API, 
then just do it in API.__init__():

class API(object):
def __init__(self, keyring):
for name, method in capabilities(keyring).iteritems():
setattr(self, name, method)

Can you show us some code? <:)


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


Re: [Re: newbie question]

2004-12-22 Thread Doug Holton
Steve Holden wrote:
> 'Scuse me? This group has a long history of off-topic posting, and
> anyway who decided that CPython should be the exclusive focus? Even
> on-topic we can talk about Jython and PyPy as well as CPython.
>
> Off-topic we can talk about what we damned well please. Even boo :-)
Thankyou, that's the most intelligent thing you've said all week.
--
http://mail.python.org/mailman/listinfo/python-list


Re: trouble building python2.4

2004-12-22 Thread Steve Holden
Matthew Thorley wrote:
I have got to be the stupidest person on the face of the planet.
I'll have you know I don't welcome newcomers to this newsgroup trying to 
steal my hard-won reputation, if you don't mind.

keeping-it-light-ly y'rs  - 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: win32 process name

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

from win32all
EnumProcesses gives me the pids, then
OpenProcess(pid) gives me a handle.
Then what?
GetModuleFileNameEX?  It requires two handles as args
and I can't figure out which one is the handle from OpenProcess
and what it wants for the other one and I can't find any
Win32 SDK docs that help.

http://msdn.microsoft.com/library/en-us/perfmon/base/getmodulefilenameex.asp
describes a function with two [in] arguments, and one [out] argument.
the first argument is the process handle, the second a module handle;
the second argument can be NULL.

This ought to be a nobrainer. But Nooo. Its Windows.

it can be pretty tricky on other platforms too; that's why Unix programs usually
solve this by writing their PID to a file in a known location, so that other 
programs
can find them without having to resort to more or less stupid tricks.
 
On Linux, you can just scan the /proc directory. This is what the procps 
package does. From the command line:

310 $ ps -o cmd --no-heading 867
metalog [MASTER]
In the pyNMS package on sourceforge 
(http://sourceforge.net/projects/pynms) there is a module called 
Linux.procfs, and in it there is an object called "ProcStat" that lets 
you get the process info easily (if running on Linux).

Python> import procfs
Python> procfs.ProcStat(1)
Python> pid1 = procfs.ProcStat(1)
Python> print pid1
cmdline: init [3]
   cmaj_flt: 63690958
   cmin_flt: 186761321
 cnswap: 0
command: (init)
eip: 35
esp: 43
exit_signal: 0
  flags: 256
  it_real_value: 0
maj_flt: 224
min_flt: 1963
mm_end_code: 134538444
  mm_start_code: 134512640
 mm_start_stack: 3221225232
   nice: 0
  nswap: 0
   pgrp: 0
pid: 1
   ppid: 0
   priority: 15
  processor: 0
   rlim_cur: 4294967295
rss: 117
session: 0
sig_blocked: 0
  sig_catch: 671819267
 sig_ignore: 1475401980
sig_pending: 0
 start_time: 42
  state: S
 tms_cstime: 731277
 tms_cutime: 9593767
  tms_stime: 237
  tms_utime: 75
 tty_nr: 0
   tty_pgrp: -1
  vsize: 1429504
  wchan: 3222957162
--
-- ~
   Keith Dart <[EMAIL PROTECTED]>
   public key: ID: F3D288E4
   =
--
http://mail.python.org/mailman/listinfo/python-list


RE: Metaclasses

2004-12-22 Thread Bob . Cowdery
Title: RE: Metaclasses





Robert


Yes you understand exectly what I am trying to do, my test code was not much more than you show. You are right that to do the simple thing of adding attributes I can do that in-line as it were but there may be other customisations that I want to do. I am probably just not understanding the process here but in both the examples you give the code is executed on 'import' so I end up with a class that has fixed function depending on what capability it picked up at 'import' time. 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'. Does that make any sense?

Bob


-Original Message-
From: Robert Brewer [mailto:[EMAIL PROTECTED]] 
Sent: 22 December 2004 17:01
To: [EMAIL PROTECTED]; python-list@python.org
Subject: RE: Metaclasses



Bob Cowdery 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. I could have several
> different instances of the api concurrently running
> against different back end services. A ui applet will
> bind to an api instance. I want to make this easy to
> use from the ui perspective so I envisage exposing a
> number of properties as the variable part can be
> represented by properties. I want a property to exist
> only if a capability is available so it is easily tested.
> I have tried using Property and Metaclasses to do this
> and although both work I can't figure out how to make multiple 
> different instances as both get executed on 'import' and thus only one 
> instance can be created. Inside the metaclass I have to get hold of 
> the capability map I want to build the instance against. The only way 
> I can see to do this at the moment is to have a metaclass
> for each capability type and hardcode the type inside it,
> then pick the appropriate metaclass when I build the
> implementation class.
 
I was with you until the last couple of sentences. :) I *think* you're trying to write something like this:


class MetaAPI(type):
    def __init__(cls, name, bases, dct):
    for name, method in capabilities.iteritems():
    setattr(cls, name, method)


class API(object):
    __metaclass__ = MetaAPI


...where all capable behaviors are attached to the API _class_.


But then you start talking about "instances", and I'm not sure whether you mean instances of the API class or not, because the metaclass doesn't have much to do with that. If you want to conditionally attach methods to instances of API, then just do it in API.__init__():

class API(object):
    def __init__(self, keyring):
    for name, method in capabilities(keyring).iteritems():
    setattr(self, name, method)


Can you show us some code? <:)



Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]



*** Confidentiality Notice *** 
Proprietary/ConfidentialInformation belonging to CGI Group Inc. and its 
affiliatesmay be contained in this message. If you are not a 
recipientindicated or intended in this message (or responsible 
fordelivery of this message to such person), or you think forany reason 
that this message may have been addressed to youin error, you may not use or 
copy or deliver this messageto anyone else.  In such case, you should 
destroy thismessage and are asked to notify the sender by reply 
email.

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

extract news article from web

2004-12-22 Thread Zhang Le
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

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


Re: File locking is impossible in Windows? SOLUTION

2004-12-22 Thread Pekka Niiranen
Hi everybody:
I played with the class Flock and changed the line
win32con.FILE_SHARE_READ|win32con.FILE_SHARE_WRITE,\
to
win32con.FILE_SHARE_READ,\
and now I cannot copy the file over which suits me.
When file is NOT locked I get:
E:\>copy d:\log.txt .
Overwrite .\log.txt? (Yes/No/All): y
1 file(s) copied.
When file IS locked I get:
E:\>copy d:\log.txt .
The process cannot access the file because it is being used by another 
process.
0 file(s) copied.

Below is the new script completely. Note that when
upgrading to Python v2.4 I had to change self.highbits
from 0x to -0x7fff.
-SCRIPT STARTS
import win32file
import win32con
import win32security
import pywintypes
class Flock:
   def __init__(self,file):
self.file=file
secur_att = win32security.SECURITY_ATTRIBUTES()
secur_att.Initialize()
self.highbits=-0x7fff
self.hfile=win32file.CreateFile( self.file,\
win32con.GENERIC_READ|win32con.GENERIC_WRITE,\
win32con.FILE_SHARE_READ,\  
secur_att,\
win32con.OPEN_ALWAYS,\
win32con.FILE_ATTRIBUTE_NORMAL , 0)
   def lock(self):
lock_flags=win32con.LOCKFILE_EXCLUSIVE_LOCK|\
win32con.LOCKFILE_FAIL_IMMEDIATELY
self.ov=pywintypes.OVERLAPPED()
win32file.LockFileEx(self.hfile,lock_flags,0,\
self.highbits,self.ov)
   def unlock(self):
win32file.UnlockFileEx(self.hfile,0,\
self.highbits,self.ov)
self.hfile.Close()
if __name__ == '__main__':
import sys
l=Flock("e:log.txt")
print 'calling lock'
l.lock()
print "Now locked.  Hit enter to release lock."
dummy = sys.stdin.readline()
l.unlock()
print 'now unlocked'
-SCRIPT ENDS
-pekka-
Pekka Niiranen wrote:
Hi,
I have used the following example from win32 extensions:
-SCRIPT STARTS
import win32file
import win32con
import win32security
import pywintypes
class Flock:
def __init__(self,file):
self.file=file
secur_att = win32security.SECURITY_ATTRIBUTES()
secur_att.Initialize()
self.highbits=-0x7fff
self.hfile=win32file.CreateFile( self.file,\
win32con.GENERIC_READ|win32con.GENERIC_WRITE,\
win32con.FILE_SHARE_READ|win32con.FILE_SHARE_WRITE,\
secur_att, win32con.OPEN_ALWAYS,\
win32con.FILE_ATTRIBUTE_NORMAL , 0 )
def lock(self):
lock_flags=win32con.LOCKFILE_EXCLUSIVE_LOCK|\
win32con.LOCKFILE_FAIL_IMMEDIATELY
self.ov=pywintypes.OVERLAPPED()
win32file.LockFileEx(self.hfile,lock_flags,0,\
self.highbits,self.ov)
def unlock(self):
win32file.UnlockFileEx(self.hfile,0,\
self.highbits,self.ov)
self.hfile.Close()
if __name__ == '__main__':
from time import time, strftime, localtime
import sys

l=Flock("e:log.txt")
print 'calling lock'
l.lock()
print "Now locked.  Hit enter to release lock."
dummy = sys.stdin.readline()

l.unlock()
print 'now unlocked'
-SCRIPT ENDS
If I start one python process from dos window I get message:
E:\>python lockker.py
calling lock
Now locked.  Hit enter to release lock.
All well, now if
1)I start another Dos -shell and run the same command I get:
E:\>python lockker.py
calling lock
Traceback (most recent call last):
  File "lockker.py", line 35, in ?
l.lock()
  File "lockker.py", line 23, in lock
   win32file.LockFileEx(self.hfile,lock_flags,0,\
   self.highbits,self.ov)
pywintypes.error: (33, 'LockFileEx',\
'The process cannot access the file because\
 another process has locked a portion of  the file.')
Which is correct.
2)I try to read the contents of the file from Dos -shell, I get:
E:\>type log.txt
The process cannot access the file because another\
process has locked a portion of the file.

This is correct.

3)When I open the file into notepad.exe I can edit the screen
but not write changes to disk. Correct again!
4)I cannot delete the file from Dos shell or from W2K explorer
which is correct.
5)However, I can overwrite the file over with:
E:\>copy d:\log.txt log.txt
1 file(s) copied.
Which is WRONG as is me being able to copy another file over it
with W2K explorer too.
Is there a way around this? How can I stop file being COPIED OVER while
it is being open? Is this window's feature? Is readlines() operation
"atomic" enough for me not to worry about these issues?
My python script modifies set of files from a directory one by one.
I try to lock them all exclusively for the script
until all are modified. If one of the files gets overwritten
by another version (by another process) the script may fail.
-pekka-





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


Re: regular expression: perl ==> python

2004-12-22 Thread Nick Craig-Wood
> 1) In perl:
> $line = "The food is under the bar in the barn.";
> if ( $line =~ /foo(.*)bar/ ) { print "got <$1>\n"; }
>
> in python, I don't know how I can do this?
> How does one capture the $1? (I know it is \1 but it is still not clear
> how I can simply print it.
> thanks


Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>  "JZ" <[EMAIL PROTECTED]> 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've found that a slight irritation in python compared to perl - the
fact that you need to create a match object (rather than relying on
the silver thread of $_ (etc) running through your program ;-)

import re
line = "The food is under the bar in the barn."
m = re.search(r'foo(.*)bar',line)
if m:
print 'got %s\n' % m.group(1)

This becomes particularly irritating when using if, elif etc, to
match a series of regexps, eg

line = "123123"
m = re.search(r'^(\d+)$', line)
if m:
   print "int",int(m.group(1))
else:
   m = re.search(r'^(\d*\.\d*)$', line)
   if m:
  print "float",float(m.group(1))
   else:
  print "unknown thing", line

The indentation keeps growing which looks rather untidy compared to
the perl

$line = "123123";
if ($line =~ /^(\d+)$/) {
print "int $1\n";
}
elsif ($line =~ /^(\d*\.\d*)$/) {
print "float $1\n";
}
else {
print "unknown thing $line\n";
}

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

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


Your message to plucker-dev awaits moderator approval

2004-12-22 Thread plucker-dev-admin
Your mail to 'plucker-dev' with the subject

Delivery ([EMAIL PROTECTED])

Is being held until the list moderator can review it for approval.

The reason it is being held:

Post by non-member to a members-only list

Either the message will get posted to the list, or you will receive
notification of the moderator's decision.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why are tuples immutable?

2004-12-22 Thread Jeff Shannon
Antoon Pardon wrote:
Op 2004-12-21, Jeff Shannon schreef <[EMAIL PROTECTED]>:
 

Antoon Pardon wrote:
   

So show us a dictionary (i.e. hash table) implementation that can do 
this.
   

Why should I, Do you doubt that it is possible?
 

Yes.
You'll need to be able to derive the old hash from the new hash, 
of course, so that you can correctly associate the values already stored 
under that key.  And you'll have to be able to do that without referring 
to the pre-modified object again, because dicts can't track every Python 
operation that might modify a key object.  And it needs to deal properly 
with equivalent-but-different-ID list literals, because using literals 
(and not references stored elsewhere) is an important and common dict 
key usage.

If you can show me how you plan to accomplish this, I'll accept that 
you're right on this.  Until then...
   

I don't have to accomplish all that in order to be able to clean up
a mutated dictionary key. All I need to do is go over the keys, see
if they hash to the same bucket as they are in now and otherwise
put them in the new bucket. Sure that would be costly, but so would
allowing arbitrary mutation in a sorted list and resorting everytime
or in a heapqueue and reheapifying.
 

The problem is that once the object has mutated, you *don't know* what 
bucket it used to sort into.  There is no point at which a dictionary 
can see "before" and "after" -- it just sees two different lists.

And yes I know what to do if I want to use mutable keys as objects. I'm
just argueing against those who think that should be somehow forbidden.
 

We're not arguing that it should be arbitrarily forbidden.  We're 
arguing that doing anything else makes it impossible to behave 
sensibly.
   

How does having stable keys in a mutable objects makes it impossible
to behave sensible for dictionaries?
 

What you are calling "stable keys in a mutable object" simply cannot be 
done while allowing comparison-by-value.  Sensible behavior for 
dictionary keys requires that it be possible to compare keys by value.  
Overall sensible behavior for lists also provides a strong suggestion 
(though not an absolute requirement) that lists should normally compare 
by value.  Your suggestion requires that lists *not* compare by value, 
and provides very little practical benefit in return for complicating 
all other list-comparison code everywhere.

So prove us wrong,
   

I don't have to prove you wrong. If you want to argue something,
you have to provide reasoning that shows you right.
 

You're the one that's saying that the current behavior is flawed.  
You're the one making the extraordinary claim that things could be done 
better.  I'm not even claiming that *I'm* right -- I'm claiming that GvR 
and Tim Peters are smarter and far more likely to be right than either 
of us. ;)

by implementing something that behaves 
sensibly in the face of mutating keys (which compare by value, as lists 
do, rather than by identity).
   

You are confusing two things with each other. That is 1) a mutable object
that is a key and 2) a mutating key. Even if an object is mutable it can
be stable for some duration and thus unmutating. There is IMO nothing
wrong with using such mutable objects as dictionary keys or in other
structures that require an invariant. Requiring that such objects be
immutable and thus can't even mutate during periods they are not so
used, creates an unnecessary burden.
 

Requiring that programmers track which objects have been used as 
dictionary keys somewhere and may still be in a dictionary creates an 
unnecessary burden, and one which *WILL* be forgotten.  If you allow 
mutable objects as keys, then key objects *WILL* mutate underneath the 
dictionary -- it's blindness to think otherwise.  That means that dicts 
would need to handle that in *some* way -- at bare minimum, throwing a 
meaningful error.  In essence, you're saying that programmers should 
mentally enforce invariants, rather than having the language enforce 
them.  Which has about as much chance of success as C's malloc/free() 
has of never being misused.

And I still say that there's a big difference between the invariant 
condition of a *core language feature* that is used everywhere 
internally in the langauge, and which therefore requires rock-solid and 
blazing-fast performance, making restrictions to prevent cases where it 
cannot behave unsurprisingly (because mutating keys, however they're 
handled, *will* surprise people), and your so-called comparison case of 
an informally-organized non-language-standard data format, done on top 
of language features rather than as part of the core, in which mutations 
are not only less surprising but much easier (i.e. actually possible) to 
compensate for.

Jeff Shannon
Technician/Programmer
Credit International
--
http://mail.python.org/mailman/listinfo/python-list


wxPython help

2004-12-22 Thread km
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 
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >