Re: BASIC vs Python

2004-12-18 Thread Gregor Horvath
Adam DePrince wrote:
On Fri, 2004-12-17 at 09:25, Steve Holden wrote:

Or make any given standard python object accessible from MS Excel in 2 
minutes.

What you describe is a political, not technical, challenge.  
What I describe is a daily costumer demand.
Like or not, the world uses Excel and costumers want to access apps from it.
--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: better lambda support in the future?

2004-12-18 Thread Terry Reedy

"Bengt Richter" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Looks like your standard pattern could be updated:
>
> >>> dispatch = {}
> >>>
> >>> def dispvia(name):
> ... def _(f, name=name):
> ... dispatch[name] = f
> ... return f
> ... return _
> ...
> >>> @dispvia('a')
> ... def handle_a(): pass
> ...
> >>> @dispvia('b')
> ... def handle_b(): pass
> ...
> >>> @dispvia('c')
> ... def handle_c(): pass
> ...
> >>> for t in sorted(dispatch.items()): print '%5s: %r'%t
> ...
> a: 
> b: 
> c: 

To avoid the redundancy of 'a' and '_a', etc, how about (untested):

def dispvia(f):
  dispatch[f.__name__.split('_')[1]] = f
  return f

? (Don't have 2.4 loaded yet)

Terry J. Reedy



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


Re: BASIC vs Python

2004-12-18 Thread Gregor Horvath
Andrew Dalke wrote:
Huh?  I'm talking about my views of myself.  I said that
BASIC was a programming language I could learn without access
to anyone else, on a microcomputer circa 1982.  All I had was
the book that came with the computer, and after a while a
book on BASIC games.
The machine I had was a TI 99/4A.  My Dad got it because the
marketing said "it's a 16 bit processor which is the wave of
the future; the other machine only have 8 bit processors."
It came with BASIC.  LOGO was available, now that others reminded
Seems that we had the same career. :-)
I liked the TI 99/4A. Mine is still running, sometimes :-)
TI really made a good job in producing a educational machine.
It was simple, and you could make good results with little effort.
Same with python today.
And whow knows, without the TI, would I post here right now?
--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cool object trick

2004-12-18 Thread Bengt Richter
On Sat, 18 Dec 2004 08:39:47 +0100, "Fredrik Lundh" <[EMAIL PROTECTED]> wrote:

>Carl Banks wrote:
>
>> For example:
>>
>> .def lookup_reference(key):
>> .
>> .return Bunch(title=title,author=author,...)
>>
>> The code quickly and easily returns a object with the desired keys.
>> The code that calls this function would access the return values
>> directly, like this:
>>
>> .m = lookupreference()
>> .print "%s was written by %s" % (m.title,m.author)
>>
>> You could still use a dict for this, but a Bunch class neater and more
>> concise (not to mention less typing).
>
>this is how your example looks in Python:
>
>def lookup_reference(key):
>...
>return dict(title=title, author=author, ...)
>
>m = lookup_reference(...)
>print "%(title)s was written by %(author)s" % m
>
>(if you fix the bug in your example, and count the characters, you'll find
>that my example is a bit shorter)
>
>with enough keys, you can also save typing by using dummy object instead
>of a dictionary, and getting rid of the locals in lookup_reference:
>
>def lookup_reference(key):
>m = object()
>m.title = ... assign directly to return struct members ...
>m.author = ...
>return m
>
>m = lookup_reference(...)
>print "%(title)s was written by %(author)s" % vars(m)
>
 >>> m = object()
 >>> m.title = 'not so fast ;-)'
 Traceback (most recent call last):
   File "", line 1, in ?
 AttributeError: 'object' object has no attribute 'title'
 >>> m=type('',(),{})()
 >>> m.title = 'not so fast ;-)'
 >>> m.title
 'not so fast ;-)'

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is this a good use for lambda

2004-12-18 Thread Terry Reedy

"Charlie Taylor" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> I find that I use lambda functions mainly for callbacks to things like
> integration or root finding routines as follows.
>
> flow = integrate(lambda x: 2.0*pi * d(x)* v(x) * sin(a(x)),xBeg, xEnd)
>
> root = findRoot(xBeg, xEnd,
>   lambda x: y2+ lp*(x-x2) -wallFunc( x )[0], tolerance=1.0E-15)

To each there own is my philosophy.  However, with multiple arguments, I 
might prefer

def f(x): return 2.0*pi * d(x)* v(x) * sin(a(x))
flow = integrate(f, xBeg, xEnd)

def g(x): return y2+ lp*(x-x2) -wallFunc( x )[0]
root = findRoot(xBeg, xEnd, g, tolerance=1.0E-15)

even if I might use lambda initially.  (And the above is in no way a 
'mess'.)

In any case, as soon as one wants to do even two things with a function --  
plot and integrate, or integrate with two methods and compare, or ditto 
with findRoot, or calculate g(root) after findRoot, one will want a 
separate def statement.

Terry J. Reedy



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


Re: Cool object trick

2004-12-18 Thread Fredrik Lundh
Bengt Richter wrote:

> >>> m = object()
> >>> m.title = 'not so fast ;-)'
> Traceback (most recent call last):
>   File "", line 1, in ?
> AttributeError: 'object' object has no attribute 'title'

>>> m = object()
>>> m.title = 'yeah, that's stupid'
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'object' object has no attribute 'title'

>>> class m: pass
>>> m.title = 'this works better'

>>> class result: pass
>>> m = result()
>>> m.title = 'this also works, and is a bit less obscure'

 



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


Re: better lambda support in the future?

2004-12-18 Thread Nick Coghlan
Terry Reedy wrote:
To avoid the redundancy of 'a' and '_a', etc, how about (untested):
def dispvia(f):
  dispatch[f.__name__.split('_')[1]] = f
  return f
A similar idea:
Py> class DispatchTable(dict):
...   def __init__(self, prefix=""):
... self._prefix = prefix
... self._ignored = len(prefix)
...   def registerAs(self, name):
... def _ (f):
...   self[name] = f
...   return f
... return _
...   def register(self, f):
... name = f.__name__
... _ignored = self._ignored
... if name[:_ignored] == self._prefix:
...   name = name[_ignored:]
... self[name] = f
... return f
...
Py> dispatcher = DispatchTable("handle_")
Py> @dispatcher.register
... def handle_a(): pass
...
Py> @dispatcher.register
... def b(): pass
...
Py> @dispatcher.registerAs("c")
... def f(): pass
...
Py> for t in sorted(dispatcher.items()): print '%5s: %r'%t
...
a: 
b: 
c: 
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why are tuples immutable?

2004-12-18 Thread Terry Reedy

"Nick Coghlan" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> Although, it looks like new-style classes currently don't apply this 
> rule - you get the default hash implementation from object no matter 
> what:
>
> Py> class NotHashable(object):
> ...   def __cmp__(self, other):
> ... return 0
> ...
> Py> hash(NotHashable())
> 10297264
> Py> d = {NotHashable(): "Hi"}
> Py> d
> {<__main__.NotHashable object at 0x009D1FF0>: 'Hi'}
>
> That may be a bug rather than a feature :)


It does seem to conflict with the doc you quoted elsewhere in this thread:
http://www.python.org/dev/doc/devel/ref/customization.html
3.3.1 Basic customization
__hash__:
 if it defines __cmp__() or __eq__() but not __hash__(), its instances will 
not be usable as dictionary keys.

Assuming your test is with 2.4, I'd submit a bug report noting the 
discrepancy.

Terry J. Reedy



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


Re: better lambda support in the future?

2004-12-18 Thread Dima Dorfman
On 2004-12-18, Terry Reedy <[EMAIL PROTECTED]> wrote:
>
> "Dima Dorfman" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>> Both languages compile all three functions (f and the two versions of
>> g) once and choose which g to return at run-time.
>
> *If* OCaml or any other 'other' language compiles the two versions of g to 
> the final and complete functions that get returned (but I don't know if 
> that is so for OCaml or and other appropriate 'other'), then it does 
> something different from and less flexible than Python.

Sorry, I glossed over the details to convey the general idea. In
OCaml, as in Python, the code is compiled once but the closure is made
at run-time.

  # f 3 == f 3;;
  - : bool = false

where "==" is the physical equality operator like Python's "is".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: better lambda support in the future?

2004-12-18 Thread Bengt Richter
On Sat, 18 Dec 2004 03:05:08 -0500, "Terry Reedy" <[EMAIL PROTECTED]> wrote:

>
>"Bengt Richter" <[EMAIL PROTECTED]> wrote in message 
>news:[EMAIL PROTECTED]
>> Looks like your standard pattern could be updated:
>>
>> >>> dispatch = {}
>> >>>
>> >>> def dispvia(name):
>> ... def _(f, name=name):
>> ... dispatch[name] = f
>> ... return f
>> ... return _
>> ...
>> >>> @dispvia('a')
>> ... def handle_a(): pass
>> ...
>> >>> @dispvia('b')
>> ... def handle_b(): pass
>> ...
>> >>> @dispvia('c')
>> ... def handle_c(): pass
>> ...
>> >>> for t in sorted(dispatch.items()): print '%5s: %r'%t
>> ...
>> a: 
>> b: 
>> c: 
>
>To avoid the redundancy of 'a' and '_a', etc, how about (untested):
>
>def dispvia(f):
>  dispatch[f.__name__.split('_')[1]] = f
>  return f
>
>? (Don't have 2.4 loaded yet)

That should work. Didn't want to retype ;-) I just wanted to get
to the experiment following -- did you notice that it takes the assignment
name from each "def dispatch ...", but it is actually re-assigning the returned 
dispatch
*dict* as the value, not a modified function? So no function was bound to any 
local name at
any time. Kind of faking the lambda thing, and allowing non-identifier keys if 
desired. E.g.,

 >>> dispatch = {}
 >>> def dispvia(name):
 ... def _(f, name=name):
 ... f.__name__ = repr(repr(name))
 ... dispatch[name] = f
 ... return dispatch
 ... return _
 ...
 >>> for k in xrange(3):
 ... @dispvia(k)
 ... def dispatch(key=k): return key
 ...
 >>> for t in sorted(dispatch.items()): print '%5r: %r' % t
 ...
 0: 
 1: 
 2: 
 >>> for t in sorted(dispatch.items()): print '%r() => %r' % (t[1], t[1]())
 ...
 () => 0
 () => 1
 () => 2

Sort of the effect of

 >>> dispatch2 = dict((k,lambda key=k:key) for k in xrange(3))
 >>> for t in sorted(dispatch2.items()): print '%20r:%r'%t
 ...
0: at 0x02EE8FB4>
1: at 0x02EF402C>
2: at 0x02EF409C>

Oops, well it's not so pretty if you want to rename the lambdas in the same 
expression:

 >>> dispatch2 = dict((k, setattr(f, '__name__', repr(repr(k)))or f) for k,f in 
 >>> ((k,lambda key=k:key) for k in xrange(3)))
 >>> for t in sorted(dispatch2.items()): print '%20r:%r'%t
 ...
0:
1:
2:
 >>> for t in sorted(dispatch.items()): print '%r() => %r' % (t[1], t[1]())
 ...
 () => 0
 () => 1
 () => 2

;-/

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


problem to compile a win32 module with Python2.4

2004-12-18 Thread vincent delft
I've a module written in C and the associated setup.py.
Work fine (and compile fine with mvc) with Python 2.3.x

Now I've installed Python 2.4 (all the rest unchanged)
When I try to compile it, I've got a message saying that .NET SDK must be
installed. 

Am I the only one having this problem (not found by looking for in Google) ?
Is this link to Python 2.4 or my own config ?

Thanks.

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


Re: problem to compile a win32 module with Python2.4

2004-12-18 Thread Fredrik Lundh
"vincent delft" wrote:

> I've a module written in C and the associated setup.py.
> Work fine (and compile fine with mvc) with Python 2.3.x
>
> Now I've installed Python 2.4 (all the rest unchanged)
> When I try to compile it, I've got a message saying that .NET SDK must be
> installed. 

the message means what it says.

> Am I the only one having this problem (not found by looking for in Google) ?

Python NET SDK returns over 200,000 hits, and another 1660 hits in google
groups; I didn't look at them all, but most of the hits on the first few pages 
are
related to this issue.

(googling for relevant parts of the exact error message can also be helpful...)

> Is this link to Python 2.4 or my own config ?

to build extensions to Python, you need to use a compiler compatible with
the compiler used to build the Python core.  as of Python 2.4, the core team
has switched from  MSVC 6.0 to MSVC 7.1 (aka Visual Studio .NET 2003).
if you don't have the commercial version, you can use the free Microsoft Visual
C++ Toolkit:

http://groups-beta.google.com/group/comp.lang.python/msg/82e240fe42381e78
http://www.vrplumber.com/programming/mstoolkit/

or MinGW:

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

 



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


Re: Troubleshooting: re.finditer() creates object even when no match found

2004-12-18 Thread Steven Bethard
Nick Coghlan wrote:
Nick Coghlan wrote:
Chris Lasher wrote:
Hello,
I really like the finditer() method of the re module. I'm having
difficulty at the moment, however, because finditer() still creates a
callable-iterator oject, even when no match is found. This is
undesirable in cases where I would like to circumvent execution of code
meant to parse out data from my finditer() object.
Take a look at itertools.tee
Bleh - I hit send instead of delete. Tee probably doesn't do what you 
want. Steve's cookbook recipe is likely a better option.
Actually, there's an equally valid solution with tee too -- check Peter 
Otten's comments at the bottom of the recipe.

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


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

2004-12-18 Thread Steven Bethard
Fredrik Lundh wrote:
Steven Bethard wrote:
The map form, in this case, parses instantly in my brain, while the listcomp
certainly takes a few cycles.  And note that I'm not talking about the typing
conciseness, but about the effort for my brain.  But maybe I'm just wired
funny :)
Well, different at least.  I find the map one harder to parse mentally.
if you have trouble parsing a function call, I'm glad I don't have to 
maintain
your Python programs...
I don't know what I said to upset you so, but I do apologize.
If you could tell me what it was about my statement (that I find a list 
comprehension to be a clearer description of program flow than a map 
application[1]) that so insulted you, I would be glad to avoid such 
comments in the future, if it would avoid such vicious replies from you.

Steve
[1] In my mind, the program flow is spelled out explicitly in the list 
comprehension and only implicitly in the map application.  Thus the list 
comprehension is clearer to me.
--
http://mail.python.org/mailman/listinfo/python-list


Re: setup.py - just what is it for ?

2004-12-18 Thread richardshea
OK thanks for the idea. I have tried this with rather strange restults.
First, in order to be sure I knew what was going on, I wrote a script,
SpawnvTestTarget0.py, which didn't do much apart from write to a file.

I then wrote another script which spawnv'd SpawnvTestTarget0.py from
within the CGI context.

This all worked fine. At this point I thought things were looking
pretty good.

I then added in a spawnv to the setup.py (ie the script I really wanted
to be able to run) but as soon as I tried that I got an 'Internal
Server Error' message.

I've also noticed that in the directions for installing it *does* say
that you should run setup.py as root which is probably at least
contributing to the problem. Anyway out of interest here is my script
...


#!/usr/bin/python2.2
"""
A script to try to run an install.py
on a webserver to which I do not have
shell access

Usage: /installshell.cgi
"""

import cgitb; cgitb.enable()
import sys, os, cgi, pickle
from Cookie import SimpleCookie
def print_headers(headers):
for k, v in headers.items():
sys.stdout.write('%s: %s\n' % (k, v))
sys.stdout.write('\n')

print_headers({'Content-type':'text/html'})

sys.stdout.write('')
sys.stdout.write('About to execute SPAWNV Command - 1')
os.spawnv(os.P_WAIT,'/usr/bin/python2.2',['python','setup.py','install'])
os.spawnv(os.P_WAIT,'/usr/bin/python2.2',['python','SpawnvTestTarget0.py','install'])
sys.stdout.write('Finished in execute of SPAWNV Command')
sys.stdout.write('')

... I've got to go to bed now but later I'm going to try just using the
script as it is - I strongly suspect the setup.py in this case is icing
rather than cake ... then again I may be demonstrating my ignorance !
thanks for your help

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


Re: Is this a good use for lambda

2004-12-18 Thread Michael Hoffman
Charlie Taylor wrote:
flow = integrate(lambda x: 2.0*pi * d(x)* v(x) * sin(a(x)),xBeg, xEnd) 
def _flow_func(x):
return 2.0 * pi * d(x) * v(x) * sin(a(x))
flow = integrate(_flow_func, xBeg, xEnd)
root = findRoot(xBeg, xEnd, 
   lambda x: y2+ lp*(x-x2) -wallFunc( x )[0], tolerance=1.0E-15)
def _root_func(x):
return y2 + lp*(x - x2) - wallFunc(x)[0]
root = findRoot(xBeg, xEnd, _root_func, tolerance=1.0e-15)
I think those are much easier to follow. I find consistent punctuation 
spacing helps readability too...
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: Troubleshooting: re.finditer() creates object even when no match found

2004-12-18 Thread Michael Hoffman
Steven Bethard wrote:
first, iterable = peek(iterable)
I really like this as a general solution to a problem that bothers me 
occasionally. IMHO it's much better than having UndoFiles or similar 
things lying about for every use case.

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


Re: PyCrust: What am I suppose to do?

2004-12-18 Thread Jim Sizelove
It's me wrote:
I am trying out PyCrust and at a lost what to do next.  With the previous
IDE I tried, the IDE pops up the console and the editor.  From the editor, I
can set up breakpoints and debug and so forth.  Yes, I can even run the
script.
With PyCrust, the nice looking 3-pane window pops up with lots of tabs...a
prompt...and then???   Where is the file I am trying to run?  Even the File
options are all greyed out...


You can try PyAlaMode instead.  Along with PyCrust, PyShell, and 
PyAlaCarte, it is part of the Py package of wxPython.  PyAlaMode allows 
you to edit and save files.  It is especially nice for trying some code 
in the interpreter, then copying that code and pasting into the editor 
window without pasting the prompts.

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


Re: BASIC vs Python

2004-12-18 Thread Alan Gauld
On Sat, 18 Dec 2004 08:41:46 +0100, Gregor Horvath
<[EMAIL PROTECTED]> wrote:

> That means that you can set a breakpoint. While the debugger stops you 
> can edit the sourcecode (to some extent) without stopping program 
> execution and let the interpreter run this new code without restarting 
> the program.

You can do that in C/C++ in some environments (within limits).
About 11 years ago I used a C++ IDE called ObjectCenter which
included a C/C++ interpreter and ran on my Sun workstation. It
was pretty cool for the time and worked quite happily on my
350Kloc C program...

If C can do it I'm sure it must be feasible in python!

Alan G.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BASIC vs Python

2004-12-18 Thread Michael Hoffman
Gregor Horvath wrote:
> Or make any given standard python object accessible from MS Excel in 2
> minutes.
from win32com.client import Dispatch
xlApp = Dispatch("Excel.Application")
xlApp.Visible = 1
xlApp.Workbooks.Add()
xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!'
xlApp.ActiveWorkbook.ActiveSheet.Cells(1,2).Value = 'Python Rules 2!'
xlApp.ActiveWorkbook.Close(SaveChanges=0)
xlApp.Quit()
del xlApp
(stolen from )
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why are tuples immutable?

2004-12-18 Thread Roy Smith
Nick Coghlan <[EMAIL PROTECTED]> wrote:
[quoting from the Reference Manual]
> If a class defines mutable objects and implements a __cmp__() 
> or __eq__() method, it should not implement __hash__(), since the dictionary 
> implementation requires that a key's hash value is immutable (if the object's 
> hash value changes, it will be in the wrong hash bucket)."

I know that's what it says, but I don't think it's good advice.  All 
that is really required is that __hash__() always returns the same value 
over the lifetime of the object, and that objects which __cmp__() the 
same always return the same hash value.  That's it.  That's all a 
dictionary cares about.

Making the object immutable is certainly the easiest way to achieve that 
goal, but it's not the only way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BASIC vs Python

2004-12-18 Thread Jan Dries
Michael Hoffman wrote:
Gregor Horvath wrote:
 > Or make any given standard python object accessible from MS Excel in 2
 > minutes.
from win32com.client import Dispatch
xlApp = Dispatch("Excel.Application")
xlApp.Visible = 1
xlApp.Workbooks.Add()
xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!'
xlApp.ActiveWorkbook.ActiveSheet.Cells(1,2).Value = 'Python Rules 2!'
xlApp.ActiveWorkbook.Close(SaveChanges=0)
xlApp.Quit()
del xlApp
(stolen from )
Nice, but not really what the OP asked for. You make Excel accessible 
from Python, instead of the other way round.

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


DNS.DiscoverNameServer query

2004-12-18 Thread hs



Hi 
Michael
 
where can I get the 
DNS packag for Python - I haven't been able to find it so 
far.
 
Thanks a lot and 
best regards.
 
Herbert
-- 
http://mail.python.org/mailman/listinfo/python-list

Maven like tool?

2004-12-18 Thread Byron Saltysiak
Hi, I'm new to Python and looking to run a large project that would
need automated builds and project reports such as unit test coverage.

Maven is a great Java software to do this - but is there something I
should use for Python? I did some searching on SF and this list but
can't figure out what tools are used by teams to manage large Python
projects (other than the obvious CVS).

One idea is to create Maven plugins and reports that would work for
Python. The plugin would offer build/test/pydoc. One report could be
based on PyLint.

Sounds like fun but I don't want to re-invent the wheel if something
is already out there then I'd rather be a user for this one than the
developer.

Thanks in advance.

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


Re: DNS.DiscoverNameServer query

2004-12-18 Thread Fredrik Lundh
> Hi Michael

eh?

> where can I get the DNS packag for Python - I haven't been able
> to find it so far.

googling for "python dns" brings up links to:

http://www.digitallumber.com/oak (server)
http://sourceforge.net/projects/pydns/ (client library)

among the first few hits -- but those are packages for the Domain Name
System, of course.  maybe you were looking for something else?

 



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


Re: DNS.DiscoverNameServer query

2004-12-18 Thread Steve Holden
Fredrik Lundh wrote:
Hi Michael

eh?

where can I get the DNS packag for Python - I haven't been able
to find it so far.

googling for "python dns" brings up links to:
http://www.digitallumber.com/oak (server)
http://sourceforge.net/projects/pydns/ (client library)
among the first few hits -- but those are packages for the Domain Name
System, of course.  maybe you were looking for something else?
 


My favorite is http://www.dnspython.org/, which is much more usable than 
others I've come across. For some reason, in the past it was quite hard 
to find with Google. Was this what you were looking for?

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: better lambda support in the future?

2004-12-18 Thread Robin Becker
Terry Reedy wrote:
"Jp Calderone" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

On Fri, 17 Dec 2004 18:16:08 -0500, Terry Reedy <[EMAIL PROTECTED]> wrote:
.

For one-off uses not eligible for lambda treatment, where you really do not 
care about the name, use the same name, such as 'f', over and over, or a 
series such as f1, f2, ,,, or f,g,h.  I have done all three in interactive 
explorations.

Terry J. Reedy

I disagree, the existence of the name itself is information as is lack 
of existence. If the name is absent there is an implication that it not 
required. An unnecessary name is visual noise.

The thing that is probably a bit stupid about lambdas (I admit to having 
done this) is

x = lambda a,b,c:...
which could just as well be written
def x(a,b,c):return .
with only a few extra characters.
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list


Re: A rational proposal

2004-12-18 Thread Raymond L. Buvel
Mike Meyer wrote:
PEP: XXX
Title: A rational number module for Python

I think it is a good idea to have rationals as part of the standard 
distribution but why not base this on the gmpy module 
(https://sourceforge.net/projects/gmpy)?  That module already provides 
good performance.  However, it does a few things that may not be good ideas.

1. Floats are converted to rationals.  I think your proposal of rational 
to float is better.

2. Fails with a TypeError when used with a complex.  Again Your proposal 
provides a better solution.

3. Fractional powers fail with a ValueError if the root is not exact. 
You do not address this in your proposal.  Could silently convert to 
float in this case but is it better to force the user to be explicit and 
use the float() operation?

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


Re: os.walk bug?

2004-12-18 Thread Alex Martelli
Adam DePrince <[EMAIL PROTECTED]> wrote:

> Each iteration of os.walk returns three parameters; one of those, dirs,
> is a list of directories within the current directory pointed at by
> root. 

Yes, it does.

> Am I correct to assume that you beleve that by changing the contents of
> dir you will affect how os.walk traverses the directories.  If so, that
> is your problem.

It's not a problem: it's a correct description of os.walk behavior.

> When looping in a for loop, it is generally good programming practice to
> assume that nothing you do within your loop will affect which
> root,dir,files tuples have been set aside to loop over.  It is likely
> that once os.walk was called, the items to be iterated over are
> predestined (i.e. assume you are iterating over a tuple.) 

"Likely"?  I think it's generally good programming practice to read the
docs.  help(os.walk) says:

When topdown is true, the caller can modify the dirnames list in-place
(e.g., via del or slice assignment), and walk will only recurse into the
subdirectories whose names remain in dirnames; this can be used to prune
the search, or to impose a specific order of visiting.  Modifying

and topdown is true by default.  The problem was just that the poster
was not using the right way to "modify the dirnames list in-place", as
he was looping on said list rather than a copy and yet modifying what he
was looping on (two suggestions i saw were "loop on a copy", once
obtained with the odd but popular Python idiom somelist[:], once with
the much more readable approach list(somelist)...).  The best
alternative is often to use a list comprehension, with somelist[:] on
the left of the assignment since you do need to modify in-place.  I.e.,
say that, generically speaking, you're trying (and failing) to do:

for item in alist:
if isnasty(item):
alist.remove(item)

changing the header to ``in alist[:]:'' or ``in list(alist):'' probably
makes this code work, but it still can't make it GOOD... good would be:

alist[:] = [item for item in alist if not isnasty(item)]


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


Re: BASIC vs Python

2004-12-18 Thread It's me

"Jan Dries" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Michael Hoffman wrote:
> > Gregor Horvath wrote:
> >
> >  > Or make any given standard python object accessible from MS Excel in
2
> >  > minutes.
> >
> > from win32com.client import Dispatch
> >
> > xlApp = Dispatch("Excel.Application")
> > xlApp.Visible = 1
> > xlApp.Workbooks.Add()
> > xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!'
> > xlApp.ActiveWorkbook.ActiveSheet.Cells(1,2).Value = 'Python Rules 2!'
> > xlApp.ActiveWorkbook.Close(SaveChanges=0)
> > xlApp.Quit()
> > del xlApp
> >
> > (stolen from )
>
> Nice, but not really what the OP asked for.

What the OP asked for isn't what was discussed neither.

> You make Excel accessible
> from Python, instead of the other way round.
>

Again, that's a political issue - not technical nor language related.
Monopolictic empire has their way of doing things and as IT slaves, we have
to obey what the master BG wants us to do.

Anyway, here's another piece I find very nice:

http://starship.python.net/crew/pirx/spam7/COMtut.PPT



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


Re: Maven like tool?

2004-12-18 Thread John Roth
"Byron Saltysiak" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
Hi, I'm new to Python and looking to run a large project that would
need automated builds and project reports such as unit test coverage.
Maven is a great Java software to do this - but is there something I
should use for Python? I did some searching on SF and this list but
can't figure out what tools are used by teams to manage large Python
projects (other than the obvious CVS).
One idea is to create Maven plugins and reports that would work for
Python. The plugin would offer build/test/pydoc. One report could be
based on PyLint.
Sounds like fun but I don't want to re-invent the wheel if something
is already out there then I'd rather be a user for this one than the
developer.
Thanks in advance.
Byron Saltysiak
Have you looked at SCons?
http://www.scons.org/
The approach seems quite interesting and has the potential
to avoid having to learn several different languages in order
to do builds, as well as the possibility to scale well.
Martin Fowler has this to say on the subject:
http://martinfowler.com/bliki/BuildLanguage.html
Besides, it's in pure Python.
John Roth 

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


RE: Cool object trick

2004-12-18 Thread Robert Brewer
Bengt Richter wrote:
>  >>> m=type('',(),{})()
>  >>> m.title = 'not so fast ;-)'
>  >>> m.title
>  'not so fast ;-)'

Now THAT is a cool object trick. :)


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


Re: A rational proposal

2004-12-18 Thread John Roth
"Mike Meyer" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
PEP: XXX
Title: A rational number module for Python
Version: $Revision: 1.4 $
Last-Modified: $Date: 2003/09/22 04:51:50 $
Author: Mike Meyer <[EMAIL PROTECTED]>
Status: Draft
Type: Staqndards
Content-Type: text/x-rst
Created: 16-Dec-2004
Python-Version: 2.5
Post-History: 30-Aug-2002
Abstract

This PEP proposes a rational number module to add to the Python
standard library.
[snip]
The ``Rational`` class shall define all the standard mathematical
operations: addition, subtraction, multiplication, division, modulo
and power.  It will also provide the methods:
- max(*args): return the largest of a list of numbers and self.
- min(*args): return the smallest of a list of numbers and self.
max() and min() are already part of the standard library.
Providing them as instance methods is quite irregular.
- decimal(): return the decimal approximation to the rational in the
current context.
This ought to be the responsibility of the decimal() constructor.
I can see including it here to avoid adding it to the decimal()
constructor, but IMO it's bad design.
- inv(): Return the inverse of self.
I presume this means that if the rational is x/y, then it
returns y/x?
Rationals will mix with all other numeric types.  When combined with an
integer type, that integer will be converted to a rational before the
operation.  When combined with a floating type - either complex or
float - the rational will be converted to a floating approximation
before the operation, and a float or complex will be returned.  The
reason for this is that floating point numbers - including complex -
are already imprecise.  To convert them to rational would give an
incorrect impression that the results of the operation are
precise.  Decimals will be converted to rationals before the
operation.  [Open question: is this the right thing to do?]
I'd prefer to have rationals converted to decimals before
the operation, for the same reason that they're converted
to floats. Decimals also have limited precision.
Rationals can be converted to floats by float(rational), and to
integers by int(rational).
If this is the case, then there is no reason to have a separate
member operation to convert rationals to decimal. Consistency
says to do it the same way for all similar operations.
...
John Roth 

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


Re: BASIC vs Python

2004-12-18 Thread It's me
Does this one count?

http://hacks.oreilly.com/pub/h/2630


"Jan Dries" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Michael Hoffman wrote:
> > Gregor Horvath wrote:
> >
> >  > Or make any given standard python object accessible from MS Excel in
2
> >  > minutes.
> >
> > from win32com.client import Dispatch
> >
> > xlApp = Dispatch("Excel.Application")
> > xlApp.Visible = 1
> > xlApp.Workbooks.Add()
> > xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!'
> > xlApp.ActiveWorkbook.ActiveSheet.Cells(1,2).Value = 'Python Rules 2!'
> > xlApp.ActiveWorkbook.Close(SaveChanges=0)
> > xlApp.Quit()
> > del xlApp
> >
> > (stolen from )
>
> Nice, but not really what the OP asked for. You make Excel accessible
> from Python, instead of the other way round.
>
> Regards,
> Jan


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


Re: A rational proposal

2004-12-18 Thread Mike Meyer
"Raymond L. Buvel" <[EMAIL PROTECTED]> writes:

> Mike Meyer wrote:
>> PEP: XXX
>> Title: A rational number module for Python
> 
>
> I think it is a good idea to have rationals as part of the standard
> distribution but why not base this on the gmpy module
> (https://sourceforge.net/projects/gmpy)?  That module already provides
> good performance.  However, it does a few things that may not be good
> ideas.

It wraps a third party package, which can't really be added to the
standard libraray. The documentation for a rationa number package in
Python should include a pointer to gmpy with a note about performance.

> 3. Fractional powers fail with a ValueError if the root is not
> exact. You do not address this in your proposal.  Could silently
> convert to float in this case but is it better to force the user to be
> explicit and use the float() operation?

You're right. Raising a rational to a rational power isn't covered,
and may produce an irrational answer. Raising a rational to a floating
point power will cause the rational to be converted to a float, as is
specified.

I think forcing the use of float is wrong, as the rational may be an
integer. I'm not sure what should be done, so this is being added as
an open issue.

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


Re: A rational proposal

2004-12-18 Thread Mike Meyer
"John Roth" <[EMAIL PROTECTED]> writes:

> "Mike Meyer" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>> PEP: XXX
>> Title: A rational number module for Python
>> The ``Rational`` class shall define all the standard mathematical
>> operations: addition, subtraction, multiplication, division, modulo
>> and power.  It will also provide the methods:
>>
>> - max(*args): return the largest of a list of numbers and self.
>> - min(*args): return the smallest of a list of numbers and self.
>
> max() and min() are already part of the standard library.
> Providing them as instance methods is quite irregular.

They don't handle decimals or rationals. This is following the lead of
the decimal package.

>> - decimal(): return the decimal approximation to the rational in the
>> current context.
>
> This ought to be the responsibility of the decimal() constructor.
> I can see including it here to avoid adding it to the decimal()
> constructor, but IMO it's bad design.

Good point. Currently, objects now how to convert themselves to int,
float and complex. Should Rational now how to convert itself to
Decimal (and conversely, decimal now how to convert itself to
Rational)?

>> - inv(): Return the inverse of self.
> I presume this means that if the rational is x/y, then it
> returns y/x?

Is this better wording:
- inv(): Return self to the power -1.


>> Rationals will mix with all other numeric types.  When combined with an
>> integer type, that integer will be converted to a rational before the
>> operation.  When combined with a floating type - either complex or
>> float - the rational will be converted to a floating approximation
>> before the operation, and a float or complex will be returned.  The
>> reason for this is that floating point numbers - including complex -
>> are already imprecise.  To convert them to rational would give an
>> incorrect impression that the results of the operation are
>> precise.  Decimals will be converted to rationals before the
>> operation.  [Open question: is this the right thing to do?]
>
> I'd prefer to have rationals converted to decimals before
> the operation, for the same reason that they're converted
> to floats. Decimals also have limited precision.

I'm of two minds about this one. One is that decimals have limited
precision. But they represent their values exactly, whereas 1E73 isn't
a 1 followed by 73 zeros when converted to an int. On the other hand,
every decimal has a rational equivalent, but not vice versa.

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


example code sought

2004-12-18 Thread Sean McIlroy
There's something quite simple I'd like to do, but I'm hampered by
lack of knowledge regarding Tkinter. If someone could help me out with
a snippet of maximally-simple code showing, in general terms, how to
do this, that would be really great. What I want to do is simply to
move a shape around on the screen using the mouse. I've looked at
Tkdnd.py but I can't seem to extract what I need from the more
involved stuff in there.

Peace,
STM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A rational proposal

2004-12-18 Thread Jp Calderone
On Sat, 18 Dec 2004 12:29:10 -0600, Mike Meyer <[EMAIL PROTECTED]> wrote:
>"Raymond L. Buvel" <[EMAIL PROTECTED]> writes:
> 
> > Mike Meyer wrote:
> >> PEP: XXX
> >> Title: A rational number module for Python
> > 
> >
> > I think it is a good idea to have rationals as part of the standard
> > distribution but why not base this on the gmpy module
> > (https://sourceforge.net/projects/gmpy)?  That module already provides
> > good performance.  However, it does a few things that may not be good
> > ideas.
> 
> It wraps a third party package, which can't really be added to the
> standard libraray. The documentation for a rationa number package in
> Python should include a pointer to gmpy with a note about performance.
> 

  This is not true.  As evidence, see the following modules:

readline
_ssl
_tkinter
_curses, _curses_panel
dbm, gdbm, _bsddb
zlib
pyexpat

  Not to mention the crazy, mega-platform specific modules like gl, 
nis, fm, sgi, and more.  Nor Python's tight dependency on another 
third party library, libc. ;)

  Note I am not advocating the use of gmpy (nor the avoidance of it), 
simply pointing out that there is ample precedent in the standard 
library for dependence on third party libraries.

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


Re: A rational proposal

2004-12-18 Thread Jp Calderone
On Sat, 18 Dec 2004 12:40:04 -0600, Mike Meyer <[EMAIL PROTECTED]> wrote:
>"John Roth" <[EMAIL PROTECTED]> writes:
> 
> > "Mike Meyer" <[EMAIL PROTECTED]> wrote in message
> > news:[EMAIL PROTECTED]
> >> PEP: XXX
> >> Title: A rational number module for Python
> >> The ``Rational`` class shall define all the standard mathematical
> >> operations: addition, subtraction, multiplication, division, modulo
> >> and power.  It will also provide the methods:
> >>
> >> - max(*args): return the largest of a list of numbers and self.
> >> - min(*args): return the smallest of a list of numbers and self.
> >
> > max() and min() are already part of the standard library.
> > Providing them as instance methods is quite irregular.
> 
> They don't handle decimals or rationals. This is following the lead of
> the decimal package.

  They do handle decimals.  They handle any object which define __cmp__, 
or the appropriate rich comparison methods.

  The Decimal type seems to define min and max so that NaNs can be 
treated specially, but I glean this understanding from only a moment 
of reading decimal.py.  Perhaps someone more well informed can declare 
definitively the purpose of these methods.

  Also, note that the signatures are not Decimal.max(*args) and 
Decimal.min(*args), but rather each takes a single decimal argument 
in addition to self and an optional context argument.  So if the goal 
is symmetry with the Decimal type, then Rational.max() and 
Rational.min() should take only one argument.

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


Re: A rational proposal

2004-12-18 Thread Tim Peters
[Jp Calderone]
...
>  The Decimal type seems to define min and max so that NaNs
> can be treated specially, but I glean this understanding from only
> a moment of reading decimal.py.  Perhaps someone more well
> informed can declare definitively the purpose of these methods.

To conform to the semantics of the min and max operations defined in
IBM's proposed standard for decimal arithmetic:

http://www2.hursley.ibm.com/decimal/

and in particular:

http://www2.hursley.ibm.com/decimal/daops.html#refmax
and
http://www2.hursley.ibm.com/decimal/daops.html#refmin

Note that this is a moving target.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A rational proposal

2004-12-18 Thread Mike Meyer
Jp Calderone <[EMAIL PROTECTED]> writes:

>   They do handle decimals.  They handle any object which define __cmp__, 
> or the appropriate rich comparison methods.

That settles that. They're gone from the proposal. So is the method
inverse, as that's simply 1/rational.

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


Re: A rational proposal

2004-12-18 Thread Terry Reedy

"Mike Meyer" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>>> Title: A rational number module for Python
>> 

1. I would call this Not Necessary but Nice.  Perhaps the time has come to 
include rationals in the Standard Library, given that its expansion will be 
a focus of the 2.5 cycle.  It certainly seems time to have such a PEP 
pushed to a formal decision.

To increase the chance of getting BDFL approval, you might search clp and 
especially pydev archives for Guido's (and maybe other developers') past 
objections and prepare to meet them.  I vaguely remember things like too 
specialized and not needed enough, need already met by third party modules, 
and the inherent clumbsiness of exact rational calculations (due to length 
growth of 'ators and the time needed to remove common factors, if one 
does).

2. The initial and debugged implementation should be in Python at least 
until the interface and behavioral specs are finalized.  Beside the obvious 
reasons, this will help the PyPy project which is currently being slowed a 
bit by the needed to rewrite C-coded modules in Python.

Terry J. Reedy



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


Re: better lambda support in the future?

2004-12-18 Thread Terry Reedy

"Bengt Richter" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Sat, 18 Dec 2004 03:05:08 -0500, "Terry Reedy" <[EMAIL PROTECTED]> 
> wrote:
>>To avoid the redundancy of 'a' and '_a', etc, how about (untested):
>>
>>def dispvia(f):
>>  dispatch[f.__name__.split('_')[1]] = f
>>  return f

> That should work. Didn't want to retype ;-) I just wanted to get
> to the experiment following -- did you notice that it takes the 
> assignment
> name from each "def dispatch ...", but it is actually re-assigning the 
> returned dispatch
> *dict* as the value, not a modified function?

Yes, I noticed that your second version of dispvia, which I snipped, 
returned dispatch instead of the nested function named _.   But I did not 
quite think thru the import of so doing.

I think one or more of these recipies might at least be worthy of the 
cookbook site so they can be easily referenced in response to future 
postings.

Terry J. Reedy



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


ActiveState Python 2.4 Woes

2004-12-18 Thread Chuck
I am having a lot of problems with this distribution.  Is anyone else?
Among many, many problems in the debugger I also see the error below when I
start PythonWin using the context menu when selecting a python file in the
windows shell explorer.  Anyone having this problem?  I done a complete
uninstall/re-install but to no avail.

Portions Copyright 1994-2004 Mark Hammond ([EMAIL PROTECTED]) - see
'Help/About PythonWin' for further copyright information.
>>> Traceback (most recent call last):
  File "C:\Python24\Lib\site-packages\pythonwin\pywin\mfc\docview.py", line
91, in CreateNewFrame
wnd.LoadFrame(self.GetResourceID(), -1, None, context) # triggers
OnCreateClient...
win32ui: LoadFrame failed

win32ui: CreateNewFrame() virtual handler (>) raised an exception
TypeError: PyCTemplate::CreateNewFrame must return a PyCFrameWnd object.


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


Re: How to set condition breakpoints?

2004-12-18 Thread Dieter Maurer
"Christopher J. Bottaro" <[EMAIL PROTECTED]> writes on Fri, 10 Dec 2004 
11:45:19 -0600:
> ...
> Hmm, thanks for the suggestions.  One more quick question.  Is it even
> possible to set a breakpoint in a class method in pdb.py?  I can't even say
> "break Class.f" without the condition.  I don't think the documentation for
> pdb is very good...=(

What happens? I can do it...

However, I had to fix "pdb" to prevent it to set the breakpoint
inside the docstring (where it is not effective).

I hope the fix found its way into the most recent Python versions
(2.3.4 and 2.4).

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


Re: ActiveState Python 2.4 Woes

2004-12-18 Thread Chuck
Just installed Python 2.4 (from Python.org) and the Win32 extesions (from
Mark's site) and am now having NO problems.  I'll report more info as I
experience it.


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


Re: better lambda support in the future?

2004-12-18 Thread Doug Holton
Jason Zheng wrote:
I'm wondering why python still has limited lambda support. What's 
stopping the developers of python to support more lisp-like lambda 
function?
See boo and its support for closures: http://boo.codehaus.org/
http://boo.codehaus.org/Closures
It works with "def" or "do", or single-line closures use {}.
x = def:
print "hello"
A closure with parameters:
c = def(x1 as int, x2 as string):
print x1, x2
Single line closures use {}
c = {print("hello")}
Single line with parameters
c = {item as string | print(item)}
#Passing closures to a method as a parameter:
def mymethod(c as callable):
c()
x = mymethod( {print("hello")} )
#passing a multi-line closure as a parameter:
x = mymethod() do():
print "hello"
#Adding a closure to an event handler:
button.Click += def ():
print("${button} was clicked!")
--
http://mail.python.org/mailman/listinfo/python-list


Re: A beginner's problem...

2004-12-18 Thread James Martin
Try deleting the Compiled Python File that was created during import -- 
extension pyc.  Then import again.

It seems to me (I'm a novice too) that, when you import a module, Python
automatically compiles it.  Then when you import it later, the compiled
version is imported if it exists.


"Amir Dekel" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hello everyone,
>
> First, I have to say that Python is one of the coolest programing
> languages I have seen.
> And now for the problem (must be a silly one):
> When I import a module I have wrote, and then I find bugs, it seems that
> I can't import it again after a fix it. It always shows the same
> problem. I try del module but it doesn't work.
> (I use Python 2.4 with the ActivePython pack (PythonWin IDE)
>
> Solution anyone?
>
> Amir


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


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

2004-12-18 Thread Terry Reedy
In respect to map(func, seq) versus [func(i) for i in seq], for 
pre-existing func, 'OP' wrote

The map form, in this case, parses instantly in my brain, while the 
listcomp
certainly takes a few cycles.  And note that I'm not talking about the 
typing
conciseness, but about the effort for my brain.  But maybe I'm just 
wired
funny :)

>> Steven Bethard wrote:
>>>Well, different at least.  I find the map one harder to parse mentally.
[and]
> [1] In my mind, the program flow is spelled out explicitly in the list 
> comprehension and only implicitly in the map application.  Thus the list 
> comprehension is clearer to me.

For pre-existing func, I slightly prefer the map form because the 
sequential program flow is *not* spelled out.  So I can more easily see the 
sequence items mapped in parallel.  On the other hand, I probably prefer 
[i-expression for i in seq] to map(lambda i: i-expression, seq) because I 
find the (unnecessary) mental construction of a function object to be a 
compensating burden.

I can easily imagine that others will find themselves more comfortably on 
one side or the other of the mental fence I find myself sitting on ;-).

Terry J. Reedy 



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


Re: better lambda support in the future?

2004-12-18 Thread Bengt Richter
On Sat, 18 Dec 2004 14:39:54 -0500, "Terry Reedy" <[EMAIL PROTECTED]> wrote:

>
>"Bengt Richter" <[EMAIL PROTECTED]> wrote in message 
>news:[EMAIL PROTECTED]
>> On Sat, 18 Dec 2004 03:05:08 -0500, "Terry Reedy" <[EMAIL PROTECTED]> 
>> wrote:
>>>To avoid the redundancy of 'a' and '_a', etc, how about (untested):
>>>
>>>def dispvia(f):
>>>  dispatch[f.__name__.split('_')[1]] = f
>>>  return f
>
>> That should work. Didn't want to retype ;-) I just wanted to get
>> to the experiment following -- did you notice that it takes the 
>> assignment
>> name from each "def dispatch ...", but it is actually re-assigning the 
>> returned dispatch
>> *dict* as the value, not a modified function?
>
>Yes, I noticed that your second version of dispvia, which I snipped, 
>returned dispatch instead of the nested function named _.   But I did not 
That's actually not the right "instead" ;-) I.e., the function _ returns
dispatch instead of the function passed to _it_ for deco-modification.

>quite think thru the import of so doing.
>
>I think one or more of these recipies might at least be worthy of the 
>cookbook site so they can be easily referenced in response to future 
>postings.
>
It is a little sneaky though, so it might not be prudent to promote
without a little more experimentation? I just like to explore ;-)

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.walk bug?

2004-12-18 Thread Terry Reedy

"Alex Martelli" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> for item in alist:
>if isnasty(item):
>alist.remove(item)
>
> changing the header to ``in alist[:]:'' or ``in list(alist):'' probably
> makes this code work, but it still can't make it GOOD... good would be:
>
> alist[:] = [item for item in alist if not isnasty(item)]

Given that the OP has verified that replacing alist with list(alist) in the 
for statement solves his problems, I agree that the listcomp is even nicer 
in that it avoids the bug trap, the over-copying of the entire list, the 
alternative of iterating in reverse, and the n**2 behavior of multiple 
correct deletes from a long list.

Terry J. Reedy



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


Re: os.walk bug?

2004-12-18 Thread Alex Martelli
Terry Reedy <[EMAIL PROTECTED]> wrote:

> "Alex Martelli" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> > for item in alist:
> >if isnasty(item):
> >alist.remove(item)
> >
> > changing the header to ``in alist[:]:'' or ``in list(alist):'' probably
> > makes this code work, but it still can't make it GOOD... good would be:
> >
> > alist[:] = [item for item in alist if not isnasty(item)]
> 
> Given that the OP has verified that replacing alist with list(alist) in the
> for statement solves his problems, 

...and that of course is crucial (using list(alist) vs alist[:] is of
course quite minor, just my pet peeve that some of us old Pythonistas go
around doign the [:] bit as if it was obvious rather than the clearer
list() call;-)...

> I agree that the listcomp is even nicer 
> in that it avoids the bug trap, the over-copying of the entire list, the
> alternative of iterating in reverse, and the n**2 behavior of multiple
> correct deletes from a long list.

Right, the O(N**2) is generally the biggie (copying the entire list is
just O(N), and with a small multiplicative constant anyway).  2.4's
``reversed'' built-in is nice for those case in which you do need
reverse iteration, of course.  But list comprehensions are often even
better for such tasks as "remove all items such that p(item)"...


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


Re: Cool object trick

2004-12-18 Thread Nick Coghlan
Robert Brewer wrote:
Bengt Richter wrote:
>>> m=type('',(),{})()
>>> m.title = 'not so fast ;-)'
>>> m.title
'not so fast ;-)'

Now THAT is a cool object trick. :)
Heh.
Look ma, Perlython!
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: A beginner's problem...

2004-12-18 Thread Mike Meyer
[Format recovered from top posting.]

"James Martin" <[EMAIL PROTECTED]> writes:
>
>
> "Amir Dekel" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>> Hello everyone,
>> First, I have to say that Python is one of the coolest programing
>> languages I have seen.
>> And now for the problem (must be a silly one):
>> When I import a module I have wrote, and then I find bugs, it seems that
>> I can't import it again after a fix it. It always shows the same
>> problem. I try del module but it doesn't work.
>> (I use Python 2.4 with the ActivePython pack (PythonWin IDE)
>>
>> Solution anyone?
> Try deleting the Compiled Python File that was created during import -- 
> extension pyc.  Then import again.
>
> It seems to me (I'm a novice too) that, when you import a module, Python
> automatically compiles it.  Then when you import it later, the compiled
> version is imported if it exists.

It compares the dates on the .py file with the .pyc file, and
recompiles the .py file if it's newer.

Doing a second import will find the module in sys.modules and not
bother looking in the file system. The solution is to reload(module)
instead of import module.

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


Re: better lambda support in the future?

2004-12-18 Thread Nick Coghlan
Bengt Richter wrote:
It is a little sneaky though, so it might not be prudent to promote
without a little more experimentation? I just like to explore ;-)
I don't think even the py-dev discussions of this settled on whether such tricks 
were "very cool" or "downright evil".

They're probably less evil than sys._getframe hacks, though :)
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: A beginner's problem...

2004-12-18 Thread Amir Dekel
Mike Meyer wrote:
Doing a second import will find the module in sys.modules and not
bother looking in the file system. The solution is to reload(module)
instead of import module.
What if I import using "from module import class"? It seems to me that I 
can't use reload then, or I just couldn't find the right syntax...
--
http://mail.python.org/mailman/listinfo/python-list


Re: BASIC vs Python

2004-12-18 Thread Mike Meyer
Dennis Lee Bieber <[EMAIL PROTECTED]> writes:

I like your categories, but you forgot one.

> On Fri, 17 Dec 2004 13:54:45 -0500, Adam DePrince <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>> I'd like to ask everybody a simple question.  How many computer
>> languages are you completely and utterly fluent in?  The reason I ask is
>
>   "Completely and utterly"? None -- they change too fast to claim
> that.

Nah. C is pretty much set. The standard libraries you need, on the
other hand, are something else.

>   Productive in?

Python, C, Eiffel, make

>   Familiar enough to at least produce code in?

FORTRAN, sh, awk

You forgot an important category here. Can debug, if not produce code
from scratch:

Common LISP, Pascal, Scheme

>   Have toyed with?

I presume these means you've written at least one program in it, and
forgotten most of the langauge since.

Logo, Erlang, ML, Prolog, Postscript, Forth, Perl, yacc, lex, Amiga
REXX, VMS batch scripts.

>   Want to forget?

MS BASIC (Apple, TRS80 and Amiga), Logo, Assembly(8080, z80, 8086,
6809, 68K, PDP-11, PDP-10), Perl, C++, Java

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


Re: A beginner's problem...

2004-12-18 Thread Mike Meyer
Amir Dekel <[EMAIL PROTECTED]> writes:

> Mike Meyer wrote:
>> Doing a second import will find the module in sys.modules and not
>> bother looking in the file system. The solution is to reload(module)
>> instead of import module.
>>  What if I import using "from module import class"? It seems to me that
> I can't use reload then, or I just couldn't find the right syntax...

I'm pretty sure you'll have to import the module and reload it. "from
module import class" still puts the module in sys.modules, so trying
to import something from it again will find it in there.

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


Re: A rational proposal

2004-12-18 Thread Nick Coghlan
Mike Meyer wrote:
max() and min() are already part of the standard library.
Providing them as instance methods is quite irregular.
They don't handle decimals or rationals. This is following the lead of
the decimal package.
As Tim pointed out - decimal has its own versions of max & min which conform to 
the decimal specification.

For the builtin in max and min, decimal's behave like any other number.
- decimal(): return the decimal approximation to the rational in the
   current context.
This ought to be the responsibility of the decimal() constructor.
I can see including it here to avoid adding it to the decimal()
constructor, but IMO it's bad design.
Actually, what's missing at the moment is the decimal equivalent of __int__, 
__float__, etc.

Generally, for new types, it is the new type's responsibility to play well with 
pre-existing types, not the other way round (think about what the __str__ method 
actually does - it's the type conversion method for turning your object into a 
string object)

Good point. Currently, objects now how to convert themselves to int,
float and complex. Should Rational now how to convert itself to
Decimal (and conversely, decimal now how to convert itself to
Rational)?
Doing either of those properly requires adding slots to the type structure 
(since you need new magic methods - __decimal__ and __rational__).

I believe the goal is to have Decimal.decimal become a builtin for Py 2.5, in 
which case, I would also hope to see a __decimal__ special method.

The correct answer would then be for Rational.rational to handle decimals in its 
constructor, and provide an implementation of __decimal__ (similar to the way 
Decimal.decimal interacts with the other builtin types).

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


Re: A beginner's problem...

2004-12-18 Thread Nick Coghlan
Amir Dekel wrote:
Mike Meyer wrote:
Doing a second import will find the module in sys.modules and not
bother looking in the file system. The solution is to reload(module)
instead of import module.
What if I import using "from module import class"? It seems to me that I 
can't use reload then, or I just couldn't find the right syntax...
Correct. Using a non-from import is actually easier when experimenting, since 
reload is easier to use.

If you have used a from-style import, you have to do this to force a reload of 
the relevant class:

Py> from module import x
Py> # Do stuff
Py> import module
Py> reload(module)
Py> from module import x
Py> # We now have the updated version of x
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


How about "pure virtual methods"?

2004-12-18 Thread Noam Raphael
Hello,
I thought about a new Python feature. Please tell me what you think 
about it.

Say you want to write a base class with some unimplemented methods, that 
subclasses must implement (or maybe even just declare an interface, with 
no methods implemented). Right now, you don't really have a way to do 
it. You can leave the methods with a "pass", or raise a 
NotImplementedError, but even in the best solution that I know of, 
there's now way to check if a subclass has implemented all the required 
methods without running it and testing if it works. Another problem with 
the existing solutions is that raising NotImplementedError usually means 
"This method might be implemented some time", and not "you must 
implement this method when you subclass me".

What I suggest is a new class, called notimplemented (you may suggest a 
better name). It would get a function in its constructor, and would just 
save a reference to it. The trick is that when a new type (a subclass of 
the default type object) is created, It will go over all its members and 
check to see if any of them is a notimplemented instance. If that is the 
case, it would not allow an instantiation of itself.

What I want is that if I have this module:
==
class BaseClass(object):
def __init__(self):
...
@notimplemented
def save_data(self, filename):
"""This method should save the internal state of the class to
a file named filename.
"""
pass
class RealClass(BaseClass):
def save_data(self, filename):
open(filename).write(self.data)
==
then if I try to instantiate BaseClass I would get an exception, but 
instantiating RealClass will be ok.

Well, what do you say?
Noam Raphael
--
http://mail.python.org/mailman/listinfo/python-list


Replace single item in tkinter ListBox

2004-12-18 Thread Zhang Le
Hello,
Is there a quick way to replace the content of a single item in
tkinter's listbox? Currently my solution is to first delete the item,
then insert a new item at the same position. I think there may be
better way.

Zhang Le

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


Re: How about "pure virtual methods"?

2004-12-18 Thread Jp Calderone
On Sun, 19 Dec 2004 01:49:50 +0200, Noam Raphael <[EMAIL PROTECTED]> wrote:
>Hello,
> 
> I thought about a new Python feature. Please tell me what you think 
> about it.
> 
> Say you want to write a base class with some unimplemented methods, that 
> subclasses must implement (or maybe even just declare an interface, with 
> no methods implemented). Right now, you don't really have a way to do 
> it. You can leave the methods with a "pass", or raise a 
> NotImplementedError, but even in the best solution that I know of, 
> there's now way to check if a subclass has implemented all the required 
> methods without running it and testing if it works.

  What about the mechanism you described below?  That can be implemented 
without any changes to the Python language or additions to the standard 
library, and does just what you want.

> Another problem with 
> the existing solutions is that raising NotImplementedError usually means 
> "This method might be implemented some time", and not "you must 
> implement this method when you subclass me".

def foobar(x, y, z):
raise NotImplementedError("Subclasses must implement this")

> 
> What I suggest is a new class, called notimplemented (you may suggest a 
> better name). It would get a function in its constructor, and would just 
> save a reference to it. The trick is that when a new type (a subclass of 
> the default type object) is created, It will go over all its members and 
> check to see if any of them is a notimplemented instance. If that is the 
> case, it would not allow an instantiation of itself.
> 
> What I want is that if I have this module:
> 
> ==
> 
> class BaseClass(object):
>  def __init__(self):
>  ...
> 
>  @notimplemented
>  def save_data(self, filename):
>  """This method should save the internal state of the class to
>  a file named filename.
>  """
>  pass
> 
> class RealClass(BaseClass):
>  def save_data(self, filename):
>  open(filename).write(self.data)
> 
> ==
> 
> then if I try to instantiate BaseClass I would get an exception, but 
> instantiating RealClass will be ok.
> 
> 
> Well, what do you say?

  It seems as though this is more in the realm of PyChecker and unit 
tests than desirable language features.  PyChecker will already point 
out when a method cannot do anything but raise an exception, as a "pure 
virtual function" does.  Unit tests, similarly, will show you where you 
forgot to implement a method, because they _will_ exercise your code.

  Nothing is preventing you from creating a base class and a 
notimplemented decorator which cooperative to make subclasses 
uninstantiable if "pure virtual methods" remain, though.

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


Re: How about "pure virtual methods"?

2004-12-18 Thread Erik Max Francis
Noam Raphael wrote:
Well, what do you say?
Raising NotImplementedError in the methods that need to be overridden is 
much more customary, more straightforward, and already works fine.

--
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
  We learn from history that we do not learn from history.
  -- Georg Friedrich Wilhelm Hegel
--
http://mail.python.org/mailman/listinfo/python-list


Plugin system; imp module head scratch

2004-12-18 Thread Dave
Hi, all,

I'm trying to implement a simple plugin framework, with some
unexpected results. I'm using Python 2.3.4 on Windows 2000.

My script loader.py loads plugin packages from a directory (in this
case its own), and checks a variable defined in the package's
__init__.py for information on the plugin.

The directory in which loader.py sits is itself a package::

plugin_test
|
+ Plugin1
||
|__init__.py
|
__init__.py
loader.py

I must be misunderstanding how the imp module works, or something.
Although the correct package is returned by my helper method, its
member variables are those of the the parent package, plugin_test.

The output of this demo is::


Directory  plugin_test

Which seems contradictory. What have I got wrong?

Best Regards,

Dave



This is plugin_test/Plugin1/__init__.py::

dir = "plugin_test/Plugin1"


This is plugin_test/__init__.py::

dir = "plugin_test"


And here is the loader script, plugin_test/loader.py::

import os
import imp

def GetPackage(name, peerFile, relPath = '.'):
"""
Return the named Python package on a
relative path from the file given
"""
path = os.path.normpath(
os.path.join(os.path.dirname(peerFile), relPath))
try:
fObj, path, descr = imp.find_module(name, [path])
except ImportError:
return None
if descr[2] != imp.PKG_DIRECTORY:
return None
try:
return imp.load_module(name, None, '', descr)
except:
return None

if __name__ == "__main__":
pkg = GetPackage("Plugin1", __file__, '.')
print pkg
print "Directory ", pkg.dir
-- 
http://mail.python.org/mailman/listinfo/python-list


Use macros in Excel via win32com

2004-12-18 Thread chris
I'm creating an excel document dynamically from scratch using Python
and the win32com module.  All is well, but now I need to add a macro to
the spreadsheet and run it (to enable some sorting features in the
spreadsheet).  I think I know how to run a macro once it's installed
(using the Run method of the excel application object...I think), but I
can't figure out how to "install" the VBA macro code into the
spreadsheet to begin with from my Python script.
Any tips appreciated.

Thanks,
Chris

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


Easy "here documents" ??

2004-12-18 Thread Jim Hill
I've done some Googling around on this and it seems like creating a here
document is a bit tricky with Python.  Trivial via triple-quoted strings
if there's no need for variable interpolation but requiring a long, long
formatted arglist via (%s,%s,%s,ad infinitum) if there is.  So my
question is:

Is there a way to produce a very long multiline string of output with
variables' values inserted without having to resort to this wacky

"""v = %s"""%(variable)

business?

Thanks,


Jim, Python no0b
-- 
"I regard NASCAR the same way I regard gay porn: I know it exists and I
know some guys like it; I just don't want to see it."  --  Z. B. Goode
-- 
http://mail.python.org/mailman/listinfo/python-list


How do I define the search path for personal library

2004-12-18 Thread les_ander
Dear all,
i have a simple question.
Suppose I have my classes such as
myClass1.py
myClass2.py
etc
which I keep in a special folder ~/py_libs

Now
suppose I have a program that is not in py_libs
but I want to do
import myClass1 # note: myClass1 is not in the current directory

how can I set the search path for python so that it can
find myClass1?
thanks

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


Re: Use macros in Excel via win32com

2004-12-18 Thread [EMAIL PROTECTED]

"chris" <[EMAIL PROTECTED]> wrote:
>I'm creating an excel document dynamically from scratch using Python
>and the win32com module.  All is well, but now I need to add a macro to
>the spreadsheet and run it (to enable some sorting features in the
>spreadsheet).  I think I know how to run a macro once it's installed
>(using the Run method of the excel application object...I think), but I
>can't figure out how to "install" the VBA macro code into the
>spreadsheet to begin with from my Python script.
>Any tips appreciated.

Here is a manual solution for Excel 2003. At the bottom of the spreadsheet,
right-click on one of the tabs (default names sheet1 sheet2 sheet3). Click
"view code" on the menu, which should bring up a Microsoft Visual Basic editor.
Select Module from the Insert menu at the top, and paste the VBA code there.



== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 
Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about "pure virtual methods"?

2004-12-18 Thread Alex Martelli
Noam Raphael <[EMAIL PROTECTED]> wrote:

> What I want is that if I have this module:
> 
> ==
> 
> class BaseClass(object):
>  def __init__(self):
>  ...
> 
>  @notimplemented
>  def save_data(self, filename):
>  """This method should save the internal state of the class to
>  a file named filename.
>  """
>  pass
> 
> class RealClass(BaseClass):
>  def save_data(self, filename):
>  open(filename).write(self.data)
> 
> ==
> 
> then if I try to instantiate BaseClass I would get an exception, but 
> instantiating RealClass will be ok.
> 
> 
> Well, what do you say?

It's already easy to do as long as you don't insist that BaseClass must
subclass object (or allow a __metaclass__ assignment there).  Basically,
what you describe is the job of a custom metaclass, because that's where
the __call__ method on classes is defined (classes being instances of
the metaclass)... much cleaner than tampering with the __new__ or
__init__ at class level.

At sketch level, you'd have, say:

def notimplemented(f):
# save some data about f somewhere if you wish, then, e.g.:
return notimplemented

import inspect

class Meta_for_NR(type):
def __init__(cls, cn, cb, cd):
super(Meta_for_NR, cls).__init__(cn, cb, cd)
abstract_methods = []
for n, v in inspect.getmembers(cls, inspect.ismethod):
if v is notimplemented: abstract_methods.append(n)
cls._abstract_methods = abstract_methods
def __call__(cls, *a, **k):
if cls._abstract_methods:
raise TypeError, ("Cannot instantiate abstract class %s."
" Abstract methods: %s." % (cls.__name__,
', '.join(cls._abstract_methods)))
return super(Meta_for_NR, cls).__call__(*a, **k)

class Base_for_NR: __metaclass__ = Meta_for_NR


Inheriting from Base_for_NR instead of inheriting from object should
give you just the behavior you desire (net of the fact that this code of
mine is untested, just a sketch -- but the key ideas shd be ok).


If you can implement this and get it into wide usage, it may well be
adopted in the standard library.  Unless there is proof by experience
that a lot of people like this approach better than the de facto
standard, such adoption is very unlikely.  But the great thing is that
it's EASY to implement your ideas and try to garner a following for
them, so you stand a chance to get them into the standard library if you
can prove they really work well and are well-liked!


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


Re: BASIC vs Python

2004-12-18 Thread Scott Robinson
On Fri, 17 Dec 2004 20:41:11 -0600, Mike Meyer <[EMAIL PROTECTED]> wrote:

>Scott Robinson <[EMAIL PROTECTED]> writes:
>
>> Forth seems better than basic, but is *weird* (I tried it for a
>> while).  I'm not sure going from Forth to C (or Python) would be much
>> easier than Basic to C or Python.  The biggest disappointment for
>> Forth was that no significant Forth chips were made (and none until it
>> was too late).  A machine designed to be run on Forth would have been
>> unbelievably powerful from the late 70s to the mid 90s (it would be
>> more painful now than the x86 legacy, but still).
>
>I think you overestimate how long the Forth chip would have been a
>serious competitor to x`the x86 line. LISP chips - which should have
>all the same advantages - didn't last that long.
>
>http://mail.python.org/mailman/listinfo/python-list


Re: A rational proposal

2004-12-18 Thread Alex Martelli
Raymond L. Buvel <[EMAIL PROTECTED]> wrote:

> Mike Meyer wrote:
> > PEP: XXX
> > Title: A rational number module for Python
> 
> 
> I think it is a good idea to have rationals as part of the standard 
> distribution but why not base this on the gmpy module 
> (https://sourceforge.net/projects/gmpy)?  That module already provides

gmpy wraps GMP, which is covered by LGPL; therefore, gmpy itself is
LGPL, and thus, sadly, cannot be included with python (otherwise,
speaking as gmpy's author, I'd be glad to fix its design to meet your
objections).


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


Re: A rational proposal

2004-12-18 Thread Paul Rubin
[EMAIL PROTECTED] (Alex Martelli) writes:
> gmpy wraps GMP, which is covered by LGPL; therefore, gmpy itself is
> LGPL, and thus, sadly, cannot be included with python (otherwise,
> speaking as gmpy's author, I'd be glad to fix its design to meet your
> objections).

There's no obstacle to including LGPL'd modules as part of the Python
distribution as long as those modules are also offered as source code.
The LGPL does place some conditions on how LGPL'd modules can be
further redistributed, which users would have to abide by; that might
or might not be considered undesirable for Python distro purposes.
There's certainly no reason the Python docs can't point to modules
like gmpy.  They already point to code and documentation that's
flat-out proprietary.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BASIC vs Python

2004-12-18 Thread Scott Robinson
On Fri, 17 Dec 2004 20:41:11 -0600, Mike Meyer <[EMAIL PROTECTED]> wrote:

>Scott Robinson <[EMAIL PROTECTED]> writes:
>
>> Forth seems better than basic, but is *weird* (I tried it for a
>> while).  I'm not sure going from Forth to C (or Python) would be much
>> easier than Basic to C or Python.  The biggest disappointment for
>> Forth was that no significant Forth chips were made (and none until it
>> was too late).  A machine designed to be run on Forth would have been
>> unbelievably powerful from the late 70s to the mid 90s (it would be
>> more painful now than the x86 legacy, but still).
>
>I think you overestimate how long the Forth chip would have been a
>serious competitor to x`the x86 line. LISP chips - which should have
>all the same advantages - didn't last that long.
>
>http://mail.python.org/mailman/listinfo/python-list


Re: Replace single item in tkinter ListBox

2004-12-18 Thread jepler
To the best of my knowledge, the only way to do this is as you describe: delete
the old item, then insert the new item.  The Tk manpage for "listbox" doesn't
describe any commands to only update an item in the list.

Actually, you may have another choice, if your Tk is new enough---Tk supports
(in 8.4, and maybe 8.3) the -listvariable configuration option on listboxes.

.>>> t = Tkinter.Tk()
.>>> v = Tkinter.Variable(t)
.>>> l = Tkinter.Listbox(t, listvariable=v); l.pack()
.>>> v.set((1,2,3))

Now, if you assemble a Python sequence 's', you can set the list's contents
to that sequence with
.>>> v.set(tuple(s))
this still doesn-t allow slice-like updating of listboxes, however.

Finally, you could subclass the Tkinter.Listbox, and replace the __setitem__
and __setslice__ methods with methods that manipulate the underlying listbox
in the appropriate ways, then create these objects instead of Tkinter.Listbox.
I'll leave that as an exercise for the reader.  Feel free to contribute the code
to the Tkinter wiki (http://tkinter.unpy.net).

Jeff


pgpWzm7qAW52n.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Cool object trick

2004-12-18 Thread Carl Banks
Bengt Richter wrote:
> m=type('',(),{})()

Nick Coghlan wrote:
> Heh.
>
> Look ma, Perlython!

I doubt anyone could perform such a ghastly hack so simply and
straightforwardly in Perl.


-- 
CARL BANKS

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


Re: Easy "here documents" ??

2004-12-18 Thread Peter Hansen
Jim Hill wrote:
I've done some Googling around on this and it seems like creating a here
document is a bit tricky with Python.  Trivial via triple-quoted strings
if there's no need for variable interpolation but requiring a long, long
formatted arglist via (%s,%s,%s,ad infinitum) if there is.  So my
question is:
Is there a way to produce a very long multiline string of output with
variables' values inserted without having to resort to this wacky
"""v = %s"""%(variable)
business?
I have no idea what a "here document" is, but there are several
alternatives to the "wacky" basic substitution with a tuple of
values.
The simplest uses a mapping type:
mydict = {'namedVal': 666}
'''v = %(namedVal)s''' % mydict
Does that let you build whatever a "here document" is?
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I define the search path for personal library

2004-12-18 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
Dear all,
i have a simple question.
Suppose I have my classes such as
myClass1.py
myClass2.py
etc
which I keep in a special folder ~/py_libs
Now
suppose I have a program that is not in py_libs
but I want to do
import myClass1 # note: myClass1 is not in the current directory
how can I set the search path for python so that it can
find myClass1?
There are several options, including the PYTHONPATH environment
variable, creating a .pth file in site-packages or somewhere
(as documented in http://www.python.org/doc/2.4/lib/module-site.html),
or even creating your own sitecustomize.py file (also documented
in the site.py module docs).
What is best depends a bit on your own environment and needs.
For example, do you just want this available at the interactive
prompt, or to all code you write, or to code that other users
on the same system will write?
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


odbc script

2004-12-18 Thread Chris
Hello,
  I posted a while back about a newbie database question and got a 
lot of great help here.  My script that I am creating has come a long way 
(For me!) and almost does what I need it too.  I am basicly using a 
dictionary to update a access database using an odbc connector.  I am able 
to connect and it seems that I am able to loop through the code to update 
all the rows I need to.  The one weird bug I seem to get is what ever is the 
last loop through doesn't seem to update the database?
Here is my code:
**
import dbi
import odbc
invdictionary = {1112:0 ,:0 ,1129:0 ,1139:1 ,1149:1 ,1159:0 ,1169:0 
,1179:0 ,1189:1 ,1199:0} # ( key : value )
invd = invdictionary.items() # convert to a list to loop 
through
myconn = odbc.odbc('testpy')# connect to database
mycursor = myconn.cursor()
for x in invd:
mycursor.execute('Update Categories Set StockStatus=? Where ProductID=? 
;',(x[1], x[0]))# run my sql update
print x[0], x[1]   # Just to help me 
debug
mycursor.close()
myconn.close()
print invdictionary  # Just to help me debug
print invd   # Just to help me 
debug

Here is the output:
*
1189 1
1159 0
1129 0
1199 0
1169 0
1139 1
 0
1112 0
1179 0
1149 1
{1189: 1, 1159: 0, 1129: 0, 1199: 0, 1169: 0, 1139: 1, : 0, 1112: 0, 
1179: 0, 1149: 1}
[(1189, 1), (1159, 0), (1129, 0), (1199, 0), (1169, 0), (1139, 1), (, 
0), (1112, 0), (1179, 0), (1149, 1)]

After I run this script All the values update correctly except the 1149 
value which never changes in the database.
I messed with this for a while and found by adding items to the dictionary 
that it never seems to update whatever is the last item to go through the 
loop.
I thought I would float it on here and see if this isn't an obvious mistake 
that I just can't see.  Any help is appreciated.


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


Re: Easy "here documents" ??

2004-12-18 Thread M.E.Farmer
I was curious so I googled , looks like a unix thing :)

http://www.faqs.org/docs/abs/HTML/here-docs.html

Ok I am with Peter on this , still clueless.
What about string replacement.

py> x = """ Hello me name is ~NAME~. \n I am ~AGE~ years old.\n
...I live in ~CITY~.\n The city of ~CITY~ is nice.\n
...I have live here for ~AGE~ years.\n
... """
py> x = x.replace('~AGE~', '12')
py> x = x.replace('~NAME~', 'Jimmy')
py> x = x.replace('~CITY~', 'Oma')

It makes your template cleaner cause you can use what you want
for the tokens, but takes more lines to do the replacements.
still clueless,
M.E.Farmer


Peter Hansen wrote:
> Jim Hill wrote:
> > I've done some Googling around on this and it seems like creating a
here
> > document is a bit tricky with Python.  Trivial via triple-quoted
strings
> > if there's no need for variable interpolation but requiring a long,
long
> > formatted arglist via (%s,%s,%s,ad infinitum) if there is.  So my
> > question is:
> >
> > Is there a way to produce a very long multiline string of output
with
> > variables' values inserted without having to resort to this wacky
> >
> > """v = %s"""%(variable)
> >
> > business?
>
> I have no idea what a "here document" is, but there are several
> alternatives to the "wacky" basic substitution with a tuple of
> values.
>
> The simplest uses a mapping type:
>
> mydict = {'namedVal': 666}
> '''v = %(namedVal)s''' % mydict
> 
> Does that let you build whatever a "here document" is?

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


Re: Easy "here documents" ??

2004-12-18 Thread vincent wehren
Peter Hansen wrote:
Jim Hill wrote:
I've done some Googling around on this and it seems like creating a here
document is a bit tricky with Python.  Trivial via triple-quoted strings
if there's no need for variable interpolation but requiring a long, long
formatted arglist via (%s,%s,%s,ad infinitum) if there is.  So my
question is:
Is there a way to produce a very long multiline string of output with
variables' values inserted without having to resort to this wacky
"""v = %s"""%(variable)
business?

I have no idea what a "here document" is, but there are several
alternatives to the "wacky" basic substitution with a tuple of
values.
OP is looking for "heredoc" syntax; in, let's say, PHP
this lets you do something like:
$foo = new foo();
$name = 'MyName';
echo <bar[1]}.
This should print a capital 'A': \x41
EOT;
AFAIK, there is no direct Python equivalent for this kind of syntax. 
Using a mapping like you suggested or the string.Template class in 
Python 2.4 still maybe improvements over what OP calls that "wacky" 
business.

--
Vincent Wehren
The simplest uses a mapping type:
mydict = {'namedVal': 666}
'''v = %(namedVal)s''' % mydict
Does that let you build whatever a "here document" is?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Plugin system; imp module head scratch

2004-12-18 Thread Keith Dart
Dave wrote:
Hi, all,
I'm trying to implement a simple plugin framework, with some
unexpected results. I'm using Python 2.3.4 on Windows 2000.
What would be the difference between a "plugin" and a regular Python module?

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


Re: Plugin system; imp module head scratch

2004-12-18 Thread Nick Coghlan
Dave wrote:
Hi, all,
I'm trying to implement a simple plugin framework, with some
unexpected results. I'm using Python 2.3.4 on Windows 2000.
My script loader.py loads plugin packages from a directory (in this
case its own), and checks a variable defined in the package's
__init__.py for information on the plugin.
Packages and modules are really rather different beasts. I wouldn't be surprised 
to find that 'find_module' and 'load_module' behave strangely when used for 
packages.

Is there any reason you can't temporarily alter sys.path and use __import__ 
normally? The behaviour of that is generally less quirky.

Anyway, I believe your specific problem is this line:
  return imp.load_module(name, None, '', descr)
Try replacing the empty string in the third argument with the path returned from 
the find_module call. (At the moment, it is pulling in the __init__.py from the 
current directory, and assigning it to the name you requested)

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


Re: Upgrading Python Article

2004-12-18 Thread Tim Roberts
JanC <[EMAIL PROTECTED]> wrote:

>Tim Roberts schreef:
>
>> I don't think that's fair.  Visual C++ 7.1 is signficantly better at
>> compliance than their past compilers.
>
>AFAIK that's only for C++, not for C...?

Yes.  Microsoft has largely chosen to ignore C99.  According to the Visual
Studio team, there has simply been no demand.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression for javadoc style comment

2004-12-18 Thread Craig Ringer
On Fri, 2004-12-17 at 09:40, Alessandro Crugnola wrote:
> Hi all,
> i need to use a regular expression to match javadoc style comments in a file,
> something like
> 
>   /**
>* Constructs a new Call instance.
>*
>* @param object the object the Function shall be executed on
>* @param func the Function that shall be executed
>* @throws IllegalArgumentException if neigther the object or the 
> function is not available.
>*/
> 
> i'm finiding many difficulties to write a valid regular expression

It would be good if you could post some of the things you've tried, and
perhaps a little more detail about what you're trying to match. Are you
trying to match the comment as a whole, eg "this is a javadoc comment",
or are you trying to extract parts of it?

--
Craig Ringer

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


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

2004-12-18 Thread Nick Craig-Wood
Steven Bethard <[EMAIL PROTECTED]> wrote:
>  map = {}
>  for key, value in sequence:
>   map.setdefault(key, []).append(value)

I was thinking about exactly that the other day, when converting some
perl to python.

[ digression: In perl, you do

  push @{$map->{$key}}, $value

If $map->{$key} doesn't exist is is autovivified into an array (since
its in array context).  Now thats exactly the sort of magic that gives
perl a bad name ;-) ]

However, one thing I noticed is that a list is created and destroyed
as the second parameter to setdefault whether or not it is used in
map, which strikes me as a bit wasteful. You obviously can't use the
same list there either.  If it was an object with a more expensive
constructor then you'd notice it more.

It would be nice if setdefault didn't evaluate the second argument
unless it needed it.  However I guess it would have to be a language
feature to do that.

Here are some timings

$ /usr/lib/python2.3/timeit.py -s 'sequence=zip(range(1000),range(1000))' 'map 
= {}
for key, value in sequence:
map.setdefault(key, []).append(value)'
1000 loops, best of 3: 1.42e+03 usec per loop

$ /usr/lib/python2.3/timeit.py -s 'sequence=zip(range(1000),[ i%11 for i in 
range(1000)])' 'map = {}
for key, value in sequence:
map.setdefault(key, []).append(value)'
1000 loops, best of 3: 1.57e+03 usec per loop

$ /usr/lib/python2.3/timeit.py -s 'sequence=zip(range(1000),range(1000))' 'map 
= {}
for key, value in sequence:
if map.has_key(key):
map[key].append(value)
else:
map[key] = [ value ]'
1000 loops, best of 3: 1.1e+03 usec per loop

$ /usr/lib/python2.3/timeit.py -s 'sequence=zip(range(1000),[ i%11 for i in 
range(1000)])' 'map = {}
for key, value in sequence:
if map.has_key(key):
map[key].append(value)
else:
map[key] = [ value ]'
1000 loops, best of 3: 1.11e+03 usec per loop


Not that timing is everything of course ;-)
-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Easy "here documents" ??

2004-12-18 Thread Nick Coghlan
Jim Hill wrote:
Is there a way to produce a very long multiline string of output with
variables' values inserted without having to resort to this wacky
"""v = %s"""%(variable)
business?
Try combining Python 2.4's subprocess module with its string Templates.
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Use macros in Excel via win32com

2004-12-18 Thread Gregor Horvath
chris wrote:
I'm creating an excel document dynamically from scratch using Python
and the win32com module.  All is well, but now I need to add a macro to
the spreadsheet and run it (to enable some sorting features in the
spreadsheet).  I think I know how to run a macro once it's installed
(using the Run method of the excel application object...I think), but I
can't figure out how to "install" the VBA macro code into the
spreadsheet to begin with from my Python script.
Any tips appreciated.
Make a xla in Excel including your VBA macro first and then create your 
spreadshet from python using that xla as template.

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


Re: A completely silly question

2004-12-18 Thread Craig Ringer
On Sat, 2004-12-18 at 00:40, Amir Dekel wrote:
> This must be the silliest question ever:
> 
> What about user input in Python? (like stdin)
> Where can I find it? I can't find any references to it in the documentation.

Under UNIX, I generally either use curses, or just put the terminal into
raw mode:

.>>> def sane():
os.system("stty sane")

.>>> def raw():
os.system("stty raw")

.>>> raw()
.>>> x = sys.stdin.read(1)
  a
.>>> sane()
.>>> x
'a'

but that's more for the benefit of others here, since you're on Windows.
Needless to say this isn't portable.

It can often be worth also using the 'echo' and 'noecho' arguments to
stty to prevent characters getting echoed in ugly places. If you do much
of this, it's probably worth just using curses, but if you have a fairly
basic app that just needs to read raw characters sometimes this approach
should be fine.

--
Craig Ringer


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


Re: Use macros in Excel via win32com

2004-12-18 Thread chris
Thanks, but the problem is that I need to create the entire Excel
document from scratch, dynamically, via the Python script.  I want the
script to add the macro code.

-Chris

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


Re: BASIC vs Python

2004-12-18 Thread Andrew Dalke
Dennis Lee Bieber wrote:
>   Ah, but you said "standard" module for Python... The
> graphics/sound extensions on your TI 99/4A were not "standard" BASIC...

I assume by "standard" you mean some sort of formal standard,
like ANSI Basic or ISO C?  If so, well, there's no "standard" Python.

What I meant is a widely used implementation.  Perhaps "off-the-shelf"
would have been an alternative word choice.

On thing I should mention is that I'm talking about Extended
BASIC, which came on a cartridge and was much more fun than
the built-in BASIC.

Ahh, and while I gave an example with the PLAY command that
was from GW-BASIC on my Heathkit.  For the TI you needed to
enter the frequencies.  I still remember that A is 440 Hz
and C is 262.


> Go to a different computer, and the commands would likely be much
> different -- and if the command was the same, the range of pixels might
> vary.

Or even the shape of the pixel, as the TRS-80 had distinctly
rectangular ones.

I don't follow your point though.  In the early 1980s there were
no microcomputers with standard anything.  What programs, other
than some trivial BASIC ones, could be ported to other platforms
without change?

>   Hmmm, as I recall, the 99/4A didn't use BASIC as the "native"
> level, but actually ran it on top of another specialized interpreter.

Don't know.  I had migrated to a Heathkit running DOS long
before I could understand those details.  I've heard that,
and looking around now I see you're right.  BTW, from
  http://computermuseum.50megs.com/brands/ti994a.htm
here's the specs for that machine
  3.3MHz, 26 K ROM, 16.25 K RAM, 32x24 character display @ 16 colors,
40x24 @ 2 colors, 256x192 graphics, 3 channels of sound, 
US$525 in 1981.  Worse than just about any mobile phone
these days.

And there's even an emulator, for people with the old
ROMs hanging around.  Wonder if my parents still have my
old computers . 

Andrew
[EMAIL PROTECTED]

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