Re: Python code and C code in the same module?

2004-11-30 Thread Fredrik Lundh
Steven Bethard wrote:

> I'd like to merge a module written in C with a module written in Python so 
> that the user can 
> access objects from either module by importing the single, merged module.
>
> Specifically, I'm looking at the collections module, which is written in C, 
> and my Bunch object, 
> which is written in Python.  I'd like the Bunch object to appear in the 
> collections module so that 
> you can do:
>
> from collections import Bunch
>
> without, of course, removing the ability to do:
>
> from collections import deque
>
> There's no need for the code to reside in the same file or anything of course 
> -- I just want the 
> different objects to appear in the same module.

the usual way to do this is to expose the C objects via the Python
module:

# foo.py
from _foo import flubb, glubb, dubb

# main.py
import foo

foo.flubb(flabb)

if you insist on doing it the other way around, you can emulate from-import
on the C level.  see e.g. the "call" function in Modules/_sre.c for an example
(but instead of calling the "func", add it to the local module; see the 
"init_sre"
function in the same module for code that adds stuff to the module dict).

 



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


Re: Random number generation from functions

2004-11-30 Thread Robert Kern
drs wrote:
Is there any way to generate random numbers based on arbitrary real valued
functions? I am looking for something like random.gauss() but with natural
log and exponential functions.
scipy[1] has a large collection of "standard" univariate pdfs, including 
normal, exponential, gamma, and the like.

One cannot generate random numbers from arbitrary real valued functions 
because a function needs to satisfy certain restrictions to be a pdf. 
For example, you cannot generate random numbers "with a log function", 
unless you restrict the domain and renormalize.

Generating random numbers from an arbitrary pdf is possible, but tricky. 
I encourage you to search the literature for "monte carlo sampling."

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


Re: python API wrapper for C++ API

2004-11-30 Thread Josiah Carlson

"Mark Doberenz" <[EMAIL PROTECTED]> wrote:
> I'm fairly new at Python, but I've got a project I really want to do.
>  
> I'm working with a real-time 3D program called Deep Creator, and it has
> a C++ API written for it.  I'm wondering what it would take to create a
> Python wrapper that would allow me to write Python programs that would
> call the C++ API.
>  
> The main issue I'm running into is that I need to create a DLL that I
> load as a plugin into Deep Creator.  I then will specify a python
> program inside Deep Creator that I want to run, and the DLL plugin will
> be the link between the python program and Deep Creator.
>  
> I'd really appreciate any ideas or issues that people see with this set
> up.

The first thing you need to decide is whether you want to call C++ from
Python, Python from C++, both, or whether you want to embed a Python
interpreter inside your application.

The standard places to look for this kind of thing are ctypes, SWIG, and
Boost.Python.

 - Josiah

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


Re: python API wrapper for C++ API

2004-11-30 Thread Fredrik Lundh
Mark Doberenz wrote:

> I'm working with a real-time 3D program called Deep Creator, and it has
> a C++ API written for it.  I'm wondering what it would take to create a
> Python wrapper that would allow me to write Python programs that would
> call the C++ API.

start here:

http://www.python.org/cgi-bin/moinmoin/IntegratingPythonWithOtherLanguages

 



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


Re: pre-PEP generic objects

2004-11-30 Thread Fredrik Lundh
Steven Bethard wrote:

> Currently, if a Python programmer makes this design decision, they are
> forced to declare a new class, and then build instances of this class.

FORCED to create a new class, and FORCED to create instances of
their own class instead of your class?  without this, Python must surely
be unusable.  no wonder nobody's ever managed to use it for anything.

 



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


Re: Question of Optionparse

2004-11-30 Thread Peter Otten
Pekka Niiranen wrote:

> How can I STOP Optionparse to process boolean
> value as parameter. See this:
> 
>  >>> parser = optparse.OptionParser()
>  >>> parser.add_option("-x",dest='xxx', action="store_true",help="xxx")
>  >>> parser.add_option("-r",dest='root',help="directory",type="string")
>  >>> args = ["-r", "d:", "-x"]
>  >>> parser.parse_args(args)
> (, [])
> 
> Last line is correct: boolean 'xxx' gets set 'True'
> and parameter 'root' to 'd:'
> 
> However when value is NOT given for '-r' but '-x' exists:
> 
>  >>> args = ["-r", "-x"]
>  >>> parser.parse_args(args)
> (, [])
> 
> This is BS: I expected 'root' to be None and 'xxx' to be 'True'.
> How can I make it so?

I think you need a callback option.

> Another question: Is there a way to store options
> directly into user defined dictionary without assignment
> like this:
> 
> my_environment_values = {}
> (options, args) = parser.parse_args()
> environment_values["xxx"] = options.xxx

environment_values.update(options.__dict__)

Full example:

import optparse

def callback(option, opt, value, parser):
rargs = parser.rargs
if rargs and not rargs[0].startswith("-"):
parser.values.root = rargs.pop(0)
else:
parser.values.root = ""

parser = optparse.OptionParser()
parser.add_option("-x", "--xtra-terrestrial", action="store_true")
parser.add_option("-r", "--root", action="callback", callback=callback)

options, args = parser.parse_args()

environment = {}
environment.update(options.__dict__)

print environment

Peter

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


Re: Protecting Python source

2004-11-30 Thread Marco Aschwanden
+1 QOTW
--
http://mail.python.org/mailman/listinfo/python-list


Get Special Folders (ie Desktop location)

2004-11-30 Thread Colin Steadman
I'm just starting out writing Python scripts (in PSP), and need to
find the location of Windows special folders such as 'My Documents'
and 'Desktop' so that I can save files in the right place.  Is there
any method I can use in Python to get these?

If I were doing this in VBScript it'd be:

  DimWSHShell
  SetWSHShell = WScript.CreateObject("WScript.Shell")
  msgbox WSHShell.SpecialFolders("Desktop")

TIA,

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


Python on Nokia Phones ?

2004-11-30 Thread Mark Doukidis
Is it DEAD ?

An exciting prospect when I first heard of Nokia's proposal.

I thought there would be a few more postings here since the idea first
surfaced around Jan 2004.

Maybe I missed something.
Can anyone on the pilot program make a comment ?
Please give me reason to hope ?

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


RE: Get Special Folders (ie Desktop location)

2004-11-30 Thread Tim Golden
[EMAIL PROTECTED]
| I'm just starting out writing Python scripts (in PSP), and need to
| find the location of Windows special folders such as 'My Documents'
| and 'Desktop' so that I can save files in the right place.  Is there
| any method I can use in Python to get these?
| 
| If I were doing this in VBScript it'd be:
| 
|   DimWSHShell
|   SetWSHShell = WScript.CreateObject("WScript.Shell")
|   msgbox WSHShell.SpecialFolders("Desktop")
| 

You can do that in Python using the pywin32 extensions
either by using the Wshell objects as you have done:



import win32com.client
WShell = win32com.client.Dispatch ("WScript.Shell")
WShell.SpecialFolders ("Desktop")



or by using the shell module from the same package.
I've got a module which wraps the common ones for
convenience:

http://tgolden.sc.sabren.com/python/winshell.html

but essentially what you're doing is this:


from win32com.shell import shell, shellcon

shell.SHGetPathFromIDList (
  shell.SHGetSpecialFolderLocation (
0, shellcon.CSIDL_DESKTOP
  )
)


TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


comment out more than 1 line at once?

2004-11-30 Thread Riko Wichmann
Dear all,
is there a way in Python to comment out blocks of code without putting a 
# in front of each line? Somethings like C's

/*
block of code here is commented out
*/
Thanks,
Riko
--
http://mail.python.org/mailman/listinfo/python-list


Re: Protecting Python source

2004-11-30 Thread Peter Maas
Grant Edwards schrieb:
On 2004-11-29, Peter Maas <[EMAIL PROTECTED]> wrote:
If the "reverse engineering" argument boils down to "protecting source
doesn't make sense" then why does Microsoft try so hard to  protect
its sources?

To avoid embarassment.
:) This cannot be the whole truth otherwise they wouldn't release
embarrasing binaries.
--
---
Peter Maas,  M+R Infosysteme,  D-52070 Aachen,  Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
---
--
http://mail.python.org/mailman/listinfo/python-list


Class methods in Python/C?

2004-11-30 Thread Craig Ringer
Hi folks

I've been doing some looking around, but have been unable to find out
how to implement class methods on Python objects written in C. "Why are
you using C?" you ask?

Yeah, so do I. However, I need to provide bindings for an application
that Python is embedded into, and thanks to Qt the bindings are going to
be both simple and quite powerful. However, I need a way to do class
methods...

If anybody has any tips on this, It'd be much appreciated.

--
Craig Ringer

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


Re: comment out more than 1 line at once?

2004-11-30 Thread Aaron Bingham
Riko Wichmann wrote:
Dear all,
is there a way in Python to comment out blocks of code without putting 
a # in front of each line? Somethings like C's

/*
block of code here is commented out
*/
No.  Why do you want this?  Any good programmer's editor will have a 
comment/uncomment feature to make it easy to comment out whole blocks of 
code at a time using the hash character ('#').

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


Re: pre-PEP generic objects

2004-11-30 Thread Peter Otten
Steven Bethard wrote:

> def __eq__(self, other):
> """x.__eq__(y) <==> x == y"""
> return (isinstance(other, self.__class__)
> and self.__dict__ == other.__dict__)

This results in an asymmetry:

>>> from bunch import Bunch
>>> class B(Bunch): pass
...
>>> B().__eq__(Bunch())
False
>>> Bunch().__eq__(B())
True

With indirect use of __eq__() this puzzling behaviour disappears:

>>> B() == Bunch()
False
>>> Bunch() == B()
False

Whether this is intended, I don't know. If someone can enlighten me...

In any case I would prefer self.__class__ == other.__class__ over
isinstance().

Peter
 

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


Python Embedding and pep-0263

2004-11-30 Thread Peter Jakubik
Hi
I am embedding Python 2.3.3 in C++ under Win2k. I am using in my App only
Python DLL and empty site.py (so that User doesn't have to install Python). The
Python Scripts contains Non-ASCII characters and i get DeprecationWarning
pep-0263.
How can i set Python File encoding from C-Code before Script starts ?

Any help would be appreciated.

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


RE: comment out more than 1 line at once?

2004-11-30 Thread Marc Boeren

> Riko Wichmann wrote:
> 
> > Dear all,
> >
> > is there a way in Python to comment out blocks of code 
> without putting 
> > a # in front of each line? Somethings like C's
> >
> > /*
> > block of code here is commented out
> > */

Well, you could fake it by doing

"""
block of code here is commented out
"""

which will work most of the time...

Cheerio, Marc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Few things

2004-11-30 Thread bearophile
Thank you for the comments and answers, and sorry for my answering
delay...

Josiah Carlson:

>Decorators can do this without additional syntax. Think @accepts and
@returns.<

The purpose of those pre-post is to write something simile and very
*clean* that states what inputs and outputs must be. This is an
example of a pre-post conditional for a sorting function taken from
that site (all this is inside the docstring of the function):

pre:
# must be a list
isinstance(a, list)

# all elements must be comparable with all other items
forall(range(len(a)),
   lambda i: forall(range(len(a)),
lambda j: (a[i] < a[j]) ^ (a[i] >= a[j])))

post[a]:
# length of array is unchanged
len(a) == len(__old__.a)

# all elements given are still in the array
forall(__old__.a, lambda e: __old__.a.count(e) == a.count(e))

# the array is sorted
forall([a[i] >= a[i-1] for i in range(1, len(a))])


Surely such things can be passed (at least as strings) to the @accepts
and @returns decorators (using a "decorate" identifier instead of @ is
probably nicer, because the @ makes Python look more like Perl, but
I've seen that lots of people have already discussed such topic). Such
testing performed by such decorators can be "switched off" with a
global boolean flag when the program is debugged and tested.
So now someone can write and let standardise a couple of good @accepts
and @returns decorators/functors :-]


>Having a 'faq' for permutation and combination generation would be
99% of the way there.<

Uh, I'm sorry, but I don't understand :-]
Aren't such functions quite well defined?


>[Fixed] Quickselect, really, doesn't gain you a whole lot. Sure, it's
a log factor faster to select a median, but many algorithms involving
selecting medians (at least the ones that I run into in CS theory) end
up repeatedly (logn times) selecting the 'kth' smallest element
(varying k's), where sorting would actually run slightly faster.<

I've done some tests with a Quickselect that I have essentially
translated and adapted to pure Python from "Numerical Recipes" (it
seems a bit faster than the Quickselect coded by Raymond Hettinger
that can be seen in the cookbook). I have seen that on my PC, on
random sequence of FP numbers, a *single* Quickselect (to find just
the median) is faster than the standard sort for lists longer than
about 3 million elements. So it's often useless.
But using Psyco, that Quickselect becomes 5-6 times faster (for long
lists), so it beats the (good) standard Sort for lists longer than
600-3000 elements. If the Quickselect works in place (as the sort)
then it returns a partially ordered list, and you can use it to
quickly select other positions (so for close positions, like the
computing of the two central values for the median, the complexity of
the second select is nearly a constant time).
So coding the Quickselect in C/Pyrex can probably make it useful.
If you are interested I can give the Python Quickselect code, etc.


>Raymond Hettinger<

I have already seen that this person is working a lot on Python, often
in the algorithmic parts.


Nick Coghlan>I believe the OP was objecting to the spelling of "this
integer literal is hex" and "this integer literal is octal".<

Right.


Josiah Carlson>Regardless, I also don't believe the "I don't like
this" without "this is the way it should be" will result in anything.<

You are right, I was mostly afraid of saying silly things... Here is:
Such syntax can be like:
number

(Putting  at the beginning of the number is probably
worse and it goes against normal base representation in mathematics,
where you often subscript the base number).

 cannot be "B" or "b" (that stands for "base") because
number can be a Hex containing B too... So  can be "_"
(this is the Subscript in TeX markup, so this agrees with normal
representation of the base)

 can be:
1)just an integer number representing the base (similar to the second
parameter of "int", this also allows to specify any base).
2) a symbol to represent a smaller class of possibilities, like 0=2,
1=8, 2=10, 3=16, 4=64. Instead
of such digits a letter can be used: a=2, b=8, c=10, etc.
I think the first option is better.

So integer numbers can be written like:
1010100111011_2
154545_10
777_8
afa35a_16
Fi3pK_64


Thank you to Carlos Ribeiro for your development of such doc string
ideas, I appreciate them :-]

Bear hugs,
Bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Design Patterns

2004-11-30 Thread Dave Cook
On 2004-11-29, Tony Ha <[EMAIL PROTECTED]> wrote:

> I wonder, can any Python guru out there translate the Java examples in the 

Should be a good exercise, and not just for gurus ;}.

> book into Python examples, or write a similar book in Python, perhaps

I've also wished for a design patterns book aimed at Python, or at least
dynamic languages with first class functions and modules.  There's a paper
Python book with "Patterns" in the title, but it has precious little content
in it related to design patterns, at least not the GOF variety.

This web book has the word "Patterns" in it, too:

http://www.brpreiss.com/books/opus7/

But looks like it's mainly data structures.  

If you do a google search, and also search the Python Cookbook

http://aspn.activestate.com/ASPN/Python/Cookbook/

you can find examples of:

Singleton
Borg
Null
Factory
Observer (including a Publish/Subscribe recipe)
Memento
State
Decorator
Masquerading and Adaptation patterns (Alex Martelli paper)
Template (another Alex Martelli paper)
Chain of Responsibility
Proxy
Prototype

There must be good examples in actual source code out there, too.

> called "Head First Design Patterns in Python". I think, this will be a 
> great addition to Python books, and a great benefit to Python community.

I just bought this book as well.  I must have adult ADD, because I do enjoy
the Head First format, though I disdained it at first.

> P.S. I am not sure is this the right news group to post this request.

Yup, this is the place. 

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


Re: Python GTK import error

2004-11-30 Thread Dave Cook
On 2004-11-23, Qianqian Fang <[EMAIL PROTECTED]> wrote:
> ImportError: /usr/lib/libgtk-x11-2.0.so.0: undefined symbol:

Try setting LD_LIBRARY_PATH:

export LD_LIBRARY_PATH=/usr/local/lib

or wherever the .so is.  If this works, add that dir to 

/etc/ld.so.conf

and run (as root)

ldconfig -v

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


Re: documentation for PyArg_ParseTupleAndKeywords

2004-11-30 Thread Pierre Barbier de Reuille
Steven Bethard a écrit :
I'm just starting to play around with the Python source.  (Specifically, 
I'm looking at adding a key argument to max/min like sorted has.)  Can 
anyone direct me to the documentation on how 
PyArg_ParseTupleAndKeywords, etc. work?  In particular, I can't figure 
out how the format arg to vgetargskeywords should be specified...

Thanks,
Steve
You have a good documentation about that on the web site ... look at 
"Python/C API" and "Extending and Embedding". The second one is more a 
tutorial when the first one is more a reference. But everything is 
explained there !

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


DB problem while trying to use Shelve

2004-11-30 Thread Roland Hedberg
Hi!
Want to use shelve in a program I'm writing, but I encounter a problem.
This is the tail of the traceback I get back:
  File "/sw/lib/python2.3/shelve.py", line 231, in open
return DbfilenameShelf(filename, flag, protocol, writeback, binary)
  File "/sw/lib/python2.3/shelve.py", line 212, in __init__
Shelf.__init__(self, anydbm.open(filename, flag), protocol, 
writeback, binary)
  File "/sw/lib/python2.3/anydbm.py", line 83, in open
return mod.open(file, flag, mode)
  File "/sw/lib/python2.3/dbhash.py", line 16, in open
return bsddb.hashopen(file, flag, mode)
  File "/sw/lib/python2.3/bsddb/__init__.py", line 186, in hashopen
d.set_flags(hflags)
bsddb._db.DBInvalidArgError: (22, 'Invalid argument')
Illegal instruction

This is on a MacOSX machine with python 2.3.3 and db 4.2
What's going on ?
And what can I do about it ?
-- Roland


smime.p7s
Description: S/MIME cryptographic signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: comment out more than 1 line at once?

2004-11-30 Thread Bernhard Herzog
Riko Wichmann <[EMAIL PROTECTED]> writes:

> I'm using emacs (with python-mode) to do most of my editing.
[...]
> Maybe I just don't know to comment out whole blocks using editor
> commands.

comment-dwim (usually bound to M-; ) comments out the region if it's
active, or, if the region is already commented, uncomments it.

   Bernhard

-- 
Intevation GmbH http://intevation.de/
Skencil   http://skencil.org/
Thuban  http://thuban.intevation.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Restricted Execution on the cheap

2004-11-30 Thread David Pokorny
Hi,

Suppose that one wants to set up a machine to accept python code from,
say, arbitrary email, and run it safely. Would the following
(somewhat draconian) precautions be sufficient?
[assume the Python code is in hack.py]

grep exechack.py ==> nothing
grep evalhack.py ==> nothing
etc... for 'import', 'builtin', 'globals','reload'
'compile', 'file', 'open', 'input', 'locals', 'vars'

Furthermore, suppose that along with the daemon that
processes the the email there is in addition a watcher daemon
that kills and restarts the email-python-runner under any of
the following conditions:

stdout > 50 MB
email-python-runner's heap is > 50 MB
email-python-runner gets stuck on a single program for more than 5 minutes

If you're interested in hacking such a device, I'm sorry to disappoint ---
it won't be up for a long time.

Thanks!
David Pokorny


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


Re: pyserial with binary data

2004-11-30 Thread Guillaume Weymeskirch
Hi,

I've got the same problem. Errno 11 is because too much data, sending
is in progress.

Fix is easy: assign a non zero value to the writeTimeout property of
your serial objet.
Then the write method will wait up to this time for sending data.

Hope that's help

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


Re: comment out more than 1 line at once?

2004-11-30 Thread Uwe Grauer
Riko Wichmann wrote:
I'm using emacs (with python-mode) to do most of my editing. also tried 
IDLE from python already, which is nice but an old dog doesn't like to 
learn new tricks :)

Maybe I just don't know to comment out whole blocks using editor 
commands. Probably the trick Marc mentions in the following post will do 
the job.

I use it to test pieces of a modules which usually is imported from 
another. For testing different parts, I usually have different __main__ 
sections in the file 

Cheers,
Riko
Riko,
if you are using emacs, try C-c # to comment out a block of code.
Unfortunally Uncomment is not bound to a key by default.
Do a key-binding for it by yourself.
Uwe
--
http://mail.python.org/mailman/listinfo/python-list


Problem with tkinter mainloop

2004-11-30 Thread k2riddim
Hello,
I'm a beginner with Python and Tkinter development.
My application parse links in an html file. And I use Tkinter to
implement a GUI. This GUI has a button to launch the parse treatment,
and a status bar to show the state of the treatment.
I know that because of the mainloop, my tkinter application freeze
while my treatment isn't finished. That's why my status bar doesn't
update herself in real time.
I wanted to use the after or the after_idle function, but I don't
really understand why it doesn't work.

My apps is build approximately like that :

---Gui.py---
class Gui(Frame):
def __init__(self):
...
def launchTreatment(self):
   b = Treatment()
   self.after(b.treatment.parse)

---Treatment.py---
class Treatment():
def __init__(self):
...
def parse(self):
   ...
   GUIinstance.status.set("state 1")
   ...
   GUIinstance.status.set("state 2")


---Main.py---
#instanciation of classes
GUIinstance = Gui
GUIinstance.mainloop()

Any help will be very appreciated, excuse my english, this is not my
native language as you can see.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: comment out more than 1 line at once?

2004-11-30 Thread Riko Wichmann
I'm using emacs (with python-mode) to do most of my editing. also tried 
IDLE from python already, which is nice but an old dog doesn't like to 
learn new tricks :)

Maybe I just don't know to comment out whole blocks using editor 
commands. Probably the trick Marc mentions in the following post will do 
the job.

I use it to test pieces of a modules which usually is imported from 
another. For testing different parts, I usually have different __main__ 
sections in the file 

Cheers,
Riko
Aaron Bingham wrote:
Riko Wichmann wrote:
Dear all,
is there a way in Python to comment out blocks of code without putting 
a # in front of each line? Somethings like C's

/*
block of code here is commented out
*/

No.  Why do you want this?  Any good programmer's editor will have a 
comment/uncomment feature to make it easy to comment out whole blocks of 
code at a time using the hash character ('#').

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


Re: Python Design Patterns

2004-11-30 Thread Tony Ha
Hello Dave,

Thanks for pointing me to the Cookbook website.

Tony Ha.


"Dave Cook" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> On 2004-11-29, Tony Ha <[EMAIL PROTECTED]> wrote:
>
> > I wonder, can any Python guru out there translate the Java examples in
the
>
> Should be a good exercise, and not just for gurus ;}.
>
> > book into Python examples, or write a similar book in Python, perhaps
>
> I've also wished for a design patterns book aimed at Python, or at least
> dynamic languages with first class functions and modules.  There's a paper
> Python book with "Patterns" in the title, but it has precious little
content
> in it related to design patterns, at least not the GOF variety.
>
> This web book has the word "Patterns" in it, too:
>
> http://www.brpreiss.com/books/opus7/
>
> But looks like it's mainly data structures.
>
> If you do a google search, and also search the Python Cookbook
>
> http://aspn.activestate.com/ASPN/Python/Cookbook/
>
> you can find examples of:
>
> Singleton
> Borg
> Null
> Factory
> Observer (including a Publish/Subscribe recipe)
> Memento
> State
> Decorator
> Masquerading and Adaptation patterns (Alex Martelli paper)
> Template (another Alex Martelli paper)
> Chain of Responsibility
> Proxy
> Prototype
>
> There must be good examples in actual source code out there, too.
>
> > called "Head First Design Patterns in Python". I think, this will be a
> > great addition to Python books, and a great benefit to Python community.
>
> I just bought this book as well.  I must have adult ADD, because I do
enjoy
> the Head First format, though I disdained it at first.
>
> > P.S. I am not sure is this the right news group to post this request.
>
> Yup, this is the place.
>
> Dave Cook


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


Re: pre-PEP generic objects

2004-11-30 Thread Nick Craig-Wood
Steven Bethard <[EMAIL PROTECTED]> wrote:
>  I promised I'd put together a PEP for a 'generic object' data type for 
>  Python 2.5 that allows one to replace __getitem__ style access with 
>  dotted-attribute style access (without declaring another class).  Any 
>  comments would be appreciated!

This sounds very much like this class which I've used to convert perl
programs to python

class Hash:
def __init__(self, **kwargs):
for key,value in kwargs.items():
setattr(self, key, value)
def __getitem__(self, x):
return getattr(self, x)
def __setitem__(self, x, y):
setattr(self, x, y)

My experience from using this is that whenever I used Hash(), I found
that later on in the refinement of the conversion it became its own
class.

So my take on the matter is that this encourages perl style
programming (just ram it in a hash, and write lots of functions acting
on it) rather than creating a specific class for the job which is dead
easy in python anyway and to which you can attach methods etc.

YMMV ;-)

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


Re: Closing files

2004-11-30 Thread Nick Coghlan
Daniel Dittmar wrote:
- that suggest a different solution; like declarations on local 
variables that say "call destructor when object goes out of scope"
You may be interested in PEP 310 (reliable acquisition/release pairs): 
http://www.python.org/peps/pep-0310.html

(Although if that idea gets adopted, it is unlikely to use the 'with' keyword - 
see PEP 3000 for the reason why)

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


Re: The use of :

2004-11-30 Thread Nick Coghlan
BJörn Lindqvist wrote:
Because it contains more non-significant symbols (, ), { and } that
"steal" the programmers attention. But consider
def f(x, y, z)
print x, y, z
to
def f(x, y, z):
print x, y, z
IMHO, the colon-less variant is more readable than the one with the colon.  
Except that it is quite acceptable to do the following:
  def f(x, y, z,
long_func_arg_name):
long_func_arg_name(x, y, z)
  def f(x, y, z,
long_func_arg_name)
long_func_arg_name(x, y, z)
The colons do a decent job of flagging the beginning of suites, mainly because 
of Python general lack of *other* punctuation (e.g. the colon would be entirely 
ineffective at improving readability if every line ended with a semi-colon).

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


Re: comment out more than 1 line at once?

2004-11-30 Thread Riko Wichmann
Ha! have just discover C-c # myself (sometimes it helps to actually look 
at the emacs menus, even if you are used to using the key-bindings :)

Better yet works "Meta-;" as Bernhard suggested, because it comments and 
un-comments marked line!

Thanks for all the helpful tips!
- Riko

Riko,
if you are using emacs, try C-c # to comment out a block of code.
Unfortunally Uncomment is not bound to a key by default.
Do a key-binding for it by yourself.
Uwe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with tkinter mainloop

2004-11-30 Thread Eric Brunel
k2riddim wrote:
Hello,
I'm a beginner with Python and Tkinter development.
My application parse links in an html file. And I use Tkinter to
implement a GUI. This GUI has a button to launch the parse treatment,
and a status bar to show the state of the treatment.
I know that because of the mainloop, my tkinter application freeze
while my treatment isn't finished. That's why my status bar doesn't
update herself in real time.
I wanted to use the after or the after_idle function, but I don't
really understand why it doesn't work.
after and after_idle won't help you: the action you register in these methods 
are called only when the main loop gets back the control, and your problem is 
precisely that the main loop does not get it...

The method you're probably looking for is update_idletasks: it updates the 
display without getting any user event. There's another method called update, 
but this one does process user events, so it may call some of your code if such 
an event is pending. This is usually not what you want to do, except in some 
very rare cases.

Here is how it may look like in your code, along with a few remarks on your 
code:
My apps is build approximately like that :
---Gui.py---
class Gui(Frame):
Why do you inherit from Frame? A Tkinter Frame is a generic container widget; 
this is not a window. IMHO, you'd better inherit from Tk for your main window or 
from Toplevel for other windows. You'd also get better control on the actual 
window, since some of the methods available on Tk and Toplevel are not available 
on other widgets (e.g. geometry or protocol)

def __init__(self):
...
def launchTreatment(self):
   b = Treatment()
   self.after(b.treatment.parse)
This cannot be your code; the after methods takes two parameters: the number of 
milliseconds to wait before the action will be called and the action itself. You 
only provide the action here. But again, the after method won't help you to get 
what you want...

---Treatment.py---
class Treatment():
def __init__(self):
...
def parse(self):
   ...
   GUIinstance.status.set("state 1")
This is where the GUIinstance.update_idletasks() should go.
   ...
   GUIinstance.status.set("state 2")
Another GUIinstance.update_idletasks() here.

---Main.py---
#instanciation of classes
GUIinstance = Gui
Again, this cannot be your code, since you do not instantiate the class here. 
The correct line should be:

GUIinstance = Gui()
It is usually far better to post a working example demonstrating the problem you 
have instead of just extracting a few lines of your whole code. This will help 
people who are willing to help to understand exactly what is going on.

HTH
--
- Eric Brunel  -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
--
http://mail.python.org/mailman/listinfo/python-list


recombination variations

2004-11-30 Thread David Siedband
The problem I'm solving is to take a sequence like 'ATSGS' and make all 
the DNA sequences it represents.  The A, T, and G are fine but the S 
represents C or G.  I want to take this input:

[ [ 'A' ] , [ 'T' ] , [ 'C' , 'G' ], [ 'G' ] , [ 'C' , 'G' ] ]
and make the list:
[ 'ATCGC' , 'ATCGG' , 'ATGGC' , 'ATGGG' ]
The code below is what I have so far:  'alphabet' is a dictionary that 
designates the set oif base pairs that each letter represents (for 
example for S above it gives C and G).  I call these ambiguous base 
pairs because they could be more then one.  Thus the function name 
'unambiguate'.  It makes a list of sequences with only A T C and Gs and 
none of the ambiguous base pair designations.

	The function 'unambiguate_bp' takes a sequence and a base pair in it 
and returns a set of sequences with that base pair replaced by each of 
it's unambiguous possibilities.

	The function unambiguate_seq takes a sequence and runs unambiguate_bp 
on each base pair in the sequence.  Each time it does a base pair it 
replaces the set of things it's working on with the output from the 
unambiguate_bp.  It's a bit confusing.  I'd like it to be clearer.

Is there a better way to do this?
--
David Siedband
generation-xml.com

def unambiguate_bp(seq, bp):
seq_set = []
for i in alphabet[seq[bp]]:
seq_set.append(seq[:bp]+i+seq[bp+1:])
return seq_set
def unambiguate_seq(seq):
result = [seq]
for i in range(len(seq)):
result_tmp=[]
for j in result:
result_tmp = result_tmp + unambiguate_bp(j,i)
   result = result_tmp
return result

alphabet = {
'A' : ['A'],
'T' : ['T'],
'C' : ['C'],
'G' : ['G'],
'W' : ['A','T'],
'M' : ['A','C'],
'R' : ['A','G'],
'Y' : ['T','C'],
'K' : ['T','G'],
'S' : ['C','G'],
'H' : ['A','T','C'],
'D' : ['A','T','G'],
'V': ['A','G','C'],
'B' : ['C','T','G'],
'N' : ['A','T','C','G']
}
--
http://mail.python.org/mailman/listinfo/python-list


Re: comment out more than 1 line at once?

2004-11-30 Thread Dave Cook
On 2004-11-30, Uwe Grauer <[EMAIL PROTECTED]> wrote:

> if you are using emacs, try C-c # to comment out a block of code.
> Unfortunally Uncomment is not bound to a key by default.

Uncomment is C-u C-c #, at least in xemacs.  Rectangle delete sometimes
works in a pinch (C-x r k, once you've marked the rectangle.)

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


Re: documentation for PyArg_ParseTupleAndKeywords

2004-11-30 Thread John Machin
Steven Bethard <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
> I'm just starting to play around with the Python source.  (Specifically, 
> I'm looking at adding a key argument to max/min like sorted has.)  Can 
> anyone direct me to the documentation on how 
> PyArg_ParseTupleAndKeywords, etc. work?  In particular, I can't figure 
> out how the format arg to vgetargskeywords should be specified...
> 

Well I just fired up the doco gadget and pasted
"PyArg_ParseTupleAndKeywords" into the Search box and the 2nd
reference it came up with was this:

manual: Python/C API Reference Manual
section: 5.5 Parsing arguments and building values 

The 1st, 3rd & 4th references were examples of calling it. 

Where were _you_ looking?

If you want a few :-) more examples, cd to the Modules directory of
your Python source tree and grep PyArg_Parse *.c
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: slicing, mapping types, ellipsis etc.

2004-11-30 Thread Nick Coghlan
Jerry Sievers wrote:
Fellow Pythonists;
I am totally puzzled on the use of slicing on mapping types and
It's generally not supported (since slices are designed to work with the 
numerical indices of a sequence, not the arbitrary keys of a mapping).

The results of d.keys(), d.values() & d.items() can all be sliced like any other 
sequence, though.

especially unsure on use of the Ellipsis... and slicing syntax that
has two or more groups seperated by comma.
Others have explained these - one point that may not have been entirely clear is 
that none of the classes in the standard library make use of these (although the 
point may have been implied by the references to PyNumeric as the place to look 
for more exact documentation. Python's own documentation of the slice() builtins 
makes reference to Numeric!).

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


Re: Python on Nokia Phones ?

2004-11-30 Thread Ville Vainio
> "Mark" == Mark Doukidis <[EMAIL PROTECTED]> writes:

Mark> An exciting prospect when I first heard of Nokia's proposal.

Mark> I thought there would be a few more postings here since the
Mark> idea first surfaced around Jan 2004.

Do realize that giants like Nokia move slow and make a minimum amount
of noise about what they are doing. They (Nokia) seemed pretty excited
about the prospects back in the June workshop:

http://www.forum.nokia.com/main/0,,4_22,00.html

I think I'll try to check out whether they have come up with a new
version. There are lots of changes happening with S60 / Symbian OS in
general ATM, so I wouldn't be surprised if they chose to delay Python
a little bit, at least as far as shipping it with the phones goes.

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


Video Catalogue

2004-11-30 Thread Rodney Dangerfield
Greetz!

Recently I started creating a CGI application for my gf that
she would use for indexing and keeping track of her video
collection.

I am relatively new to python so I started with the basics.
I figured out how to extract the form field values in a
script and how to save to a file.

My question is which data type should I use to store the information
about the videos? I was thinking of using a dictionary variable,
I saw something about the pickle module too, could I use it to
save the state of my dictionary to a file and than later read it
and feed values from it to the form fields via CGI?

All help is greatly appreciated.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] Re: SysLogHandler is drivin me nuts PEBCAC

2004-11-30 Thread Vinay Sajip
Jan Dries <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
> Slightly OT, but regarding the title, shouldn't it be PEBKAC, since it's 
> keyboard and not ceyboard?
> 

PEBCAC: Problem Exists Between Chair And Computer
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Restricted Execution on the cheap

2004-11-30 Thread Duncan Booth
David Pokorny wrote:

> Suppose that one wants to set up a machine to accept python code from,
> say, arbitrary email, and run it safely. Would the following
> (somewhat draconian) precautions be sufficient?
> [assume the Python code is in hack.py]
> 
> grep exechack.py ==> nothing
> grep evalhack.py ==> nothing
> etc... for 'import', 'builtin', 'globals','reload'
> 'compile', 'file', 'open', 'input', 'locals', 'vars'
> 

Assuming you think *very* hard about everything that someone might try. 

Your list above certainly isn't enough though. I'm pretty sure you also 
need to block getattr otherwise:

>>> def f(): pass
>>> getattr(getattr(f, 
'shap_tybonyf'.decode('rot13'))['__ohvygvaf__'.decode('rot13')], 
'x\x9cK\xce\xcf-\xc8\xccI\x05\x00\x0b\xaf\x02\xea'.decode('zip'))


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


Re: Python Huffman encoding

2004-11-30 Thread Guyon Morée
Wow Paul!

thanks a lot for your comments! I learned a lot already only by reading
them, I will implement them and see what the speed gains are.

Keep an eye on my blog, I will post an update on it soon!


thanks,
guyon

ps. love this group


"Paul McGuire" <[EMAIL PROTECTED]> wrote in message

>
http://gumuz.looze.net/wordpress/index.php/archives/2004/11/25/huffman-encoding/

> Great first step at some self-learning with a non-trivial test program.
> Here are some performance speedups that will help you out.


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


Re: [OT] Re: SysLogHandler is drivin me nuts PEBCAC

2004-11-30 Thread Jan Dries
[Jan Dries] 
> Slightly OT, but regarding the title, shouldn't it be PEBKAC, 
> since it's 
> keyboard and not ceyboard?

[Vinay Sajip]
> PEBCAC: Problem Exists Between Chair And Computer

Interesting. I thought it was "Problem Exists Between Keyboard And Chair".
But this makes sensee too, of course. Nonetheless, Google has about 17000
references for PEBKAC, and only 381 for PEBCAC.

Regards,
Jan


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


RELEASED Python 2.4 (final)

2004-11-30 Thread Anthony Baxter
On behalf of the Python development team and the Python community, I'm
happy to announce the release of Python 2.4.

Python 2.4 is a final, stable release, and we can recommend that Python
users upgrade to this version.

Python 2.4 is the result of almost 18 month's worth of work on top 
of Python 2.3 and represents another stage in the careful evolution 
of Python. New language features have been kept to a minimum, many 
bugs have been fixed and a wide variety of improvements have been made.

Notable changes in Python 2.4 include improvements to the importing of
modules, generator expressions, function decorators, a number of new 
modules (including subprocess, decimal and cookielib) and countless 
numbers of fixed bugs and smaller enhancements. For more, see the 
(subjective) highlights, the release notes, or Andrew Kuchling's What's 
New In Python, all available from the 2.4 web page.

http://www.python.org/2.4/

Please log any problems you have with this release in the SourceForge
bug tracker (noting that you're using Python 2.4):

http://sourceforge.net/bugs/?group_id=5470

Enjoy the new (stable!) release,
Anthony

Anthony Baxter
[EMAIL PROTECTED]
Python Release Manager
(on behalf of the entire python-dev team)


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

Re: pre-PEP generic objects

2004-11-30 Thread Nick Coghlan
The proposed use cases sound more appropriate for a "named tuple" than any sort 
of dictionary. (This may have been mentioned in previous discussions. I wasn't 
keeping track of those, though)

Notice that I've used 'fromPairs' rather than 'fromMapping', since consistent 
order matters for a tuple. Comparison semantics are inherited directly from 
tuple, and don't care about names (they're only interested in values).

Also, it seems like there has to be a better way to do the "opposite of zip()" 
in fromPairs(), but I sure as hell can't think of it.

Cheers,
Nick.
>>> a = named_tuple(['x', 'y'], (3, 8))
>>> a
named_tuple(['x', 'y'], (3, 8))
>>> a.x
3
>>> a.y
8
>>> str(a)
'(3, 8)'
>>> b = named_tuple.fromPairs(sorted({'x':3, 'y':8}.items()))
>>> b
named_tuple(['x', 'y'], (3, 8))
>>> b.x
3
>>> b.y
8
>>> str(b)
'(3, 8)'
>>> a == b
True
>>>
And the code for the above:
class named_tuple(tuple):
def __new__(cls, names, *args):
self = tuple.__new__(cls, *args)
self._names = dict(zip(names, range(len(names
return self
@staticmethod
def fromPairs(items):
names = [x[0] for x in items]
values = [x[1] for x in items]
return named_tuple(names, values)
def __getattr__(self, attr):
if attr in self._names:
return self[self._names[attr]]
else:
return tuple.__getattr__(attr)
def __repr__(self):
return "named_tuple(%s, %s)" % (str(self.names()),
str(tuple.__repr__(self)))
def __str__(self):
return tuple.__repr__(self)
def names(self):
return sorted(self._names.keys(), key=self._names.__getitem__)
--
http://mail.python.org/mailman/listinfo/python-list


Re: asynchat and threading

2004-11-30 Thread Anthony Baxter
On Mon, 29 Nov 2004 23:24:54 -0500, Caleb Hattingh <[EMAIL PROTECTED]> wrote:
> I heartily support something like this, but alas I have not the time to
> help out with it.  I like the Enthought python distribution because it
> installs several packages in one shot.  A pity there isn't a similar thing
> for python addons in Linux (or is there?).

Plenty of people would like to see this. Alas, no-one has stepped forward
to do the work (or, if you have money but no time, to offer to fund the work).

Python runs on volunteers - no-one's done this yet, so it's not happened.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class methods in Python/C?

2004-11-30 Thread Nick Coghlan
Craig Ringer wrote:
Hi folks
I've been doing some looking around, but have been unable to find out
how to implement class methods on Python objects written in C. "Why are
you using C?" you ask?
Yeah, so do I. However, I need to provide bindings for an application
that Python is embedded into, and thanks to Qt the bindings are going to
be both simple and quite powerful. However, I need a way to do class
methods...
If anybody has any tips on this, It'd be much appreciated.
You probably want to look at staticmethod(). (classmethod() is slightly 
different, and probably not what you want. In fact, classmethod() is practically 
*never* what you want. Guido wrote it himself, and even he ended up not using it)

class Demo(object):
  def some_static_method(some_arg_list):
pass
  some_static_method = staticmethod(some_static_method)
Then call the function as:
  Demo.some_static_method(some_args)
In Py2.4, the method definition can be collapsed to:
class Demo(object):
  @staticmethod
  def some_static_method(some_arg_list):
pass
Cheers,
Nick.
--
http://mail.python.org/mailman/listinfo/python-list


Re: UML and OO design tool with Python support

2004-11-30 Thread mep
Any free UML modelling tools that generate python code?


-- 
Best Regards,
Wang Kebo

http://www.huihoo.org/~mep



"Paul McGuire" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> I just found out that my favorite UML modeling tool, Enterprise Architect,
> has just released a new version, *with* Python code support.  You can
> download EA at http://www.sparxsystems.com.au.  It is not free, but I
think
> it is very reasonably priced for the features it provides (under $200
gives
> you good UML graphical modeling, including sequence and class diagrams,
with
> code reverse engineering and round-tripping, vs. $000's for comparable
> Rational environment).
>
> Well, as it turns out, the Python support is still a bit buggy but I have
> already gotten good mileage from this tool in other applications, most
> notably reverse engineering C++ and C# code, so the Python additions are
> icing on the cake.  But it is certainly another reassuring note, to see
the
> inclusion of Python support into this commercial software development
tool.
>
> I've already started to forward bug reports for some of the Python import
> errors.  Perhaps if they get more feedback from other Python users, it
will
> help reinforce their opinion of Pythonistas as a valuable target market
> segment.
>
> -- Paul
>
>
> Note: I am *not* an employee or in any way connected with the supplier of
> this code, other than as a satistifed customer.
>
> Note2: the Python support is not an obvious product feature.  It requires
> installation of a separate (free) add-in, downloaded from the Sparxsystems
> web site.  The add-in must be separately "add-in"ed to each project, too,
> instead of just being a globally installed plug-in.  My first couple of
> attempts failed at completely reverse engineering my pyparsing module,
> although I did get a nice first-pass class inheritance diagram for PIL.
We
> take what we can get...
>
>


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


Re: slicing, mapping types, ellipsis etc.

2004-11-30 Thread Kent Johnson
Nick Coghlan wrote:
Jerry Sievers wrote:
Fellow Pythonists;
I am totally puzzled on the use of slicing on mapping types and

It's generally not supported (since slices are designed to work with the 
numerical indices of a sequence, not the arbitrary keys of a mapping).
Section 5.3.3 of the Language Reference seems to say that with extended 
slicing, the slice elements are used to create a key that indexes a 
mapping. "The semantics for an extended slicing are as follows. The 
primary must evaluate to a mapping object, and it is indexed with a key 
that is constructed from the slice list, as follows."

From my understanding of this thread so far, extended slicing is used 
as a form of indexing in Numeric. Are Numeric arrays considered 
mappings? Or is this paragraph in 5.3.3 off the mark?

Maybe instead of referring to mappings it should say "The primary must 
implement __getitem__(), which is called with a value that is 
constructed from the slice list, as follows."

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


weird behaviour of "0 in [] is False"

2004-11-30 Thread Sylvain Thenault
Hi there !

Can someone explain me the following behaviour ?

>>> l = []
>>> 0 in (l is False)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: iterable argument required
>>> (0 in l) is False
True
>>> 0 in l is False
False


This is really obscur to me...

-- 
Sylvain Thénault   LOGILAB, Paris (France).

http://www.logilab.com   http://www.logilab.fr  http://www.logilab.org


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


Re: Restricted Execution on the cheap

2004-11-30 Thread Nick Coghlan
David Pokorny wrote:
Hi,
Suppose that one wants to set up a machine to accept python code from,
say, arbitrary email, and run it safely. Would the following
(somewhat draconian) precautions be sufficient?
In short, no. Python's introspection capabilities kill you. There are too many 
ways to spell things to be certain all the loopholes are closed.

For instance, take a look at the result of:
  type(sys.stdout)
Sure, you can add 'type' to the banned list, but eventually the banned list is 
so long, writing a useful program is damn near impossible. 'chr' and '__dict__', 
for instance, would almost certainly have to be on the banned list, otherwise:

  key1 = ''.join([chr(x) for x in [95, 95, 98, 117, 105, 108, 116, 105, 110, 
95, 95]])
  key2 = ''.join([chr(x) for x in [102, 105, 108, 101]])
  sys.modules[key1].__dict__[key2]

It isn't accidental that Bastion and rexec got deprecated - the developers just 
can't guarantee that the modules are actually providing adequate protection.

A chroot() jail, setuid() to some permission-less sandbox user and your 
monitoring daemon are likely to get you a lot further.

Regards,
Nick.
P.S. Both examples above are bizarre ways of spelling 'file', for anyone who 
can't be bothered figuring it out.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python API wrapper for C++ API

2004-11-30 Thread Philippe C. Martin
Hi,

How about first using a C to C++ wrapper:

***
#ifdef __cplusplus

extern "C" { /* I really dislike this - iwj. */
#endif

void * init (void)
{
return new myobj()
}



 3D_fun1 (void * p_obj)
{
My_OBJ * l_obj = (My_OBJ *) p_obj;

l_obj-> 3D_Meth1()  
}

#ifdef __cplusplus
}
#endif  /* __cplusplus */

***

Then wrap this with the standard python extension stuff 

??








-- 
*
SnakeCard LLC
www.snakecard.com
*
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python code and C code in the same module?

2004-11-30 Thread Nick Coghlan
Fredrik Lundh wrote:
if you insist on doing it the other way around,
This paragraph should actually continue ". . .you clearly have too much free 
time" };>

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


Re: RELEASED Python 2.4 (final)

2004-11-30 Thread Dave Merrill
Newb question: Is it possible/recommended  to have multiple versions of
Python installed simultaneously? Earlier, I installed 2.4rc1, and a number
of things in my 2.3.3 install stopped working. Are there known techniques
for managing multiple versions?

Thanks,

Dave Merrill


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


dynamical linking problem

2004-11-30 Thread wab104
I compiled Python on one Linux box and copied it to another Linux box.
 This causes an import problem:

>>> import urllib
Traceback (most recent call last):
  File "", line 1, in ?
  File "/edl3/wb104/analysis/python2.2/lib/python2.2/urllib.py", line
26, in ?
import socket
  File "/edl3/wb104/analysis/python2.2/lib/python2.2/socket.py", line
41, in ?
from _socket import *
ImportError: libssl.so.0.9.7: cannot open shared object file: No such
file or directory

On the first Linux box I have:
  /usr/lib/libssl.so -> /usr/lib/libssl.so.0.9.7
  /usr/lib/libssl.so.0.9.7

On the second Linux box I have:
  /usr/lib/libssl.so -> /lib/lib/libssl.o.0.9.7a
  /lib/lib/libssl.o.0.9.7a

If I create an extra symbolic link on the second Linux box with name
libssl.so.0.9.7 (and also one for libcrypto, which has a similar
problem) then all is fine.

But the problem is that I want to ship a binary distribution to third
parties who might not be so confident to do this (and might think I've
shipped a duff product).

Why is the Linux linker looking for the specific libssl.so.0.9.7
rather than the generic libssl.so?  (Obviously on the first Linux box
the generic is pointing to the specific, but that's hardly a good
excuse.)  Is there any (sensible) way to convince it to do otherwise? 
This problem makes creating binary distributions difficult.  (What are
the odds that people have exactly the same version of every system
library?)
-- 
http://mail.python.org/mailman/listinfo/python-list


Bookmark CGI in Python

2004-11-30 Thread Michael Foord
Anyone written an online bookmarks manager in Python ?

I can knock a simple one together... but wondered if anyone else had
already done it ? I can't find one with google - but htere are *loads*
in perl and PHP, so I suspect thayt someoen must have written one
witrh python. One that uses XBEL would be nice - but it's not that
important.

Regards,

Fuzzy
http://www.voidspace.org.uk/atlantibots/pythonutils.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: weird behaviour of "0 in [] is False"

2004-11-30 Thread Diez B. Roggisch
 l = []
 0 in (l is False)
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: iterable argument required

that should be clear - 0 in False can't work.

 (0 in l) is False
> True
 0 in l is False
> False

It seems to stem from a behaviour python exhibits in expressions like this:

3 > 2  > 1

This yields True, while

(3 > 2 ) > 1

yields false. Chaining of operators gets translated like this:

3 > 2 and 2 > 1

Look in section 5.9 of the language reference.

Then your expression gets translated to:

0 in l and l is False

which yields False of course.


-- 
Regards,

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


Syntax for extracting multiple items from a dictionary

2004-11-30 Thread shark
row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken", "state" :
"Alaska"}
cols = ("city", "state")

Is there a best-practices way to ask for an object containing only the keys
named in cols out of row? In other words, to get this:
{"city" : "Hoboken", "state" : "Alaska"}

Thanks,

shark


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


Re: recombination variations

2004-11-30 Thread Dennis Benzinger
David Siedband wrote:
> [...] 
> Is there a better way to do this?
> [...]

Take a look at Biopython: http://biopython.org/

Your problem may be solved there already.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: weird behaviour of "0 in [] is False"

2004-11-30 Thread Duncan Booth
Sylvain Thenault wrote:

> Hi there !
> 
> Can someone explain me the following behaviour ?
> 
 l = []
 0 in (l is False)
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: iterable argument required
 (0 in l) is False
> True
 0 in l is False
> False
> 
> 
> This is really obscur to me...
> 

>From the language reference (5.9 Comparisons):

> comparison  ::=  or_expr ( comp_operator or_expr )* 
> comp_operator  ::=  "<" | ">" | "==" | ">=" | "<=" | "<>" | "!=" 
> | "is" ["not"] | ["not"] "in" 
>
> ...snip...
>
> Formally, if a, b, c, ..., y, z are expressions and opa, opb, ..., opy
> are comparison operators, then a opa b opb c ...y opy z is equivalent
> to a opa b and b opb c and ... y opy z, except that each expression is
> evaluated at most once. 

In other words '0 in l is False' is equivalent to '0 in l and l is False'.

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


Re: RELEASED Python 2.4 (final)

2004-11-30 Thread Stefan Behnel
Dave Merrill schrieb:
Newb question: Is it possible/recommended  to have multiple versions of
Python installed simultaneously? Earlier, I installed 2.4rc1, and a number
of things in my 2.3.3 install stopped working. Are there known techniques
for managing multiple versions?
Short answer: depends on your OS.
I assume "stopped working" means: libraries were missing. This means that 
"managing multiple versions" already works for you. The libraries are 
installed for Python 2.3 and only 2.3 uses them. That's the expected 
behaviour. Install them for 2.4 as well and everything should work fine.

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


Re: pdb with emacs

2004-11-30 Thread Heike C. Zimmerer
"Yuri Shtil" <[EMAIL PROTECTED]> writes:

> I am trying to learn python and use the gud/pdb from emacs. The
> functionality that I am used to under gud/gdb and gud/perldb is missing, or
> I don't know how to make it work.
> Specifically: when I start pdb on a script file, the source does not show in
> an another window as it does with perldb and gdb. If I bring it up in an
> another window,

Your source will show up when you step into your program, e.g. by
doing an "S" pdb command.

> the ^X SPC set a break, but the subsequent gud-next commands do not move the
> execution cursor in the source file window.

I never use gud's commands while in pdb mode because they didn't work
- at least not as I expected - and I've already been familiar with pdb
syntax.  You'd better use pdb commands in its debugger window.


Greetings,

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


Re: MySQLdb problem with mod_python, please help

2004-11-30 Thread Damjan
> MySQLdb is working fine at command line, however when I tried to use
> it with mod_python, it give me a "server not initialized" error.

Maybe its this problem?
http://www.modpython.org/FAQ/faqw.py?req=show&file=faq02.013.htp

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


Re: weird behaviour of "0 in [] is False"

2004-11-30 Thread Sylvain Thenault
On Tue, 30 Nov 2004 14:18:30 +0100, Diez B. Roggisch wrote:

> l = []
> 0 in (l is False)
>> Traceback (most recent call last):
>>   File "", line 1, in ?
>> TypeError: iterable argument required
> 
> that should be clear - 0 in False can't work.

yes, I forget to mention that it was the third expression which was
bugging me.

> (0 in l) is False
>> True
> 0 in l is False
>> False
> 
> It seems to stem from a behaviour python exhibits in expressions like
> this:
> 
> 3 > 2  > 1
> 
> This yields True, while
> 
> (3 > 2 ) > 1
> 
> yields false. Chaining of operators gets translated like this:
> 
> 3 > 2 and 2 > 1
> 
> Look in section 5.9 of the language reference.
> 
> Then your expression gets translated to:
> 
> 0 in l and l is False
> 
> which yields False of course.

thanks, I had missed this part of the language reference !
Not yet found an misbehaviour in python... ;)

-- 
Sylvain Thénault   LOGILAB, Paris (France).

http://www.logilab.com   http://www.logilab.fr  http://www.logilab.org


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


Re: comment out more than 1 line at once?

2004-11-30 Thread Roy Smith
Riko Wichmann <[EMAIL PROTECTED]> wrote:
> I'm using emacs (with python-mode) to do most of my editing. also tried 
> IDLE from python already, which is nice but an old dog doesn't like to 
> learn new tricks :)

Emacs is great for stuff like this.  There's probably other ways to do 
it, but what I would do is a quick keyboard macro.  Go to the beginning 
of the first line and type:

C-X ( # C-A C-N C-X )

That defines a macro which inserts a # then moves to the beginning of 
the next line.  Then you need to execute that once for each additional 
line you want to comment out.  If there's 17 additional lines, you would 
do:

C-U 1 7 C-X E

Hmmm.  I just did help-appropos on "comment" and of course I found the 
better way I suspected must exist :-)  You can just use M-X 
comment-region or M-X py-comment-region.

Still, learning how to do keyboard macros will really improve your 
productivity in emacs.  There's often a better way to do something, but 
for simple repetitive tasks, you can often write and execute a keyboard 
macro faster than you can look up the better way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RELEASED Python 2.4 (final)

2004-11-30 Thread Anthony Baxter
On Tue, 30 Nov 2004 08:05:55 -0500, Dave Merrill <[EMAIL PROTECTED]> wrote:
> Newb question: Is it possible/recommended  to have multiple versions of
> Python installed simultaneously? Earlier, I installed 2.4rc1, and a number
> of things in my 2.3.3 install stopped working. Are there known techniques
> for managing multiple versions?

If you're building from source, use 'make altinstall' rather than
'make install'.
This will install Python as $prefix/bin/python2.4, and leave the
'python' executable
alone.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class methods in Python/C?

2004-11-30 Thread Jp Calderone
On Tue, 30 Nov 2004 22:39:15 +1000, Nick Coghlan <[EMAIL PROTECTED]> wrote:
>Craig Ringer wrote:
> > Hi folks
> > 
> > I've been doing some looking around, but have been unable to find out
> > how to implement class methods on Python objects written in C. "Why are
> > you using C?" you ask?
> > 
> > Yeah, so do I. However, I need to provide bindings for an application
> > that Python is embedded into, and thanks to Qt the bindings are going to
> > be both simple and quite powerful. However, I need a way to do class
> > methods...
> > 
> > If anybody has any tips on this, It'd be much appreciated.
> 
> You probably want to look at staticmethod(). (classmethod() is slightly 
> different, and probably not what you want. In fact, classmethod() is 
> practically 
> *never* what you want. Guido wrote it himself, and even he ended up not using 
> it)

  Funny, I find the exact opposite to be the case... ;)  Static methods are 
glorified free functions, but class methods participate usefully in inheritence 
hierarchies - why would anyone want the former?

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


Re: RELEASED Python 2.4 (final)

2004-11-30 Thread Dave Merrill
Should have been more specific.

As I recall, after I installed 2.4rc1 I installed the latest versions of
wxWindows and SPE IDE into it. The 2.4 copy of SPE died silently when
started, which I can accept as a incompatible versions.

What was strange to me was that at that point, the 2.3.3 copy of SPE did the
same thing. After I uninstalled 2.4, SPE ran again under 2.3.3, and that's
what I'm using now.

What caused this kind of interaction between installs? SPE and wxWindows
both live in site-packages, which I would have thought would make them
Python-version specific.

Dave Merrill

"Stefan Behnel" wrote:
>
> Dave Merrill schrieb:
> > Newb question: Is it possible/recommended  to have multiple versions of
> > Python installed simultaneously? Earlier, I installed 2.4rc1, and a
number
> > of things in my 2.3.3 install stopped working. Are there known
techniques
> > for managing multiple versions?
>
> Short answer: depends on your OS.
>
> I assume "stopped working" means: libraries were missing. This means that
> "managing multiple versions" already works for you. The libraries are
> installed for Python 2.3 and only 2.3 uses them. That's the expected
> behaviour. Install them for 2.4 as well and everything should work fine.
>
> Stefan


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


Re: RELEASED Python 2.4 (final)

2004-11-30 Thread Anthony Baxter
On Tue, 30 Nov 2004 08:53:25 -0500, Dave Merrill <[EMAIL PROTECTED]> wrote:
> Should have been more specific.
> 
> As I recall, after I installed 2.4rc1 I installed the latest versions of
> wxWindows and SPE IDE into it. The 2.4 copy of SPE died silently when
> started, which I can accept as a incompatible versions.
> 
> What was strange to me was that at that point, the 2.3.3 copy of SPE did the
> same thing. After I uninstalled 2.4, SPE ran again under 2.3.3, and that's
> what I'm using now.
> 
> What caused this kind of interaction between installs? SPE and wxWindows
> both live in site-packages, which I would have thought would make them
> Python-version specific.

Beats me. You could try running SPE from a command line and seeing
what errors it spits out - you're probably going to need to talk to
whoever packaged up SPE.

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


Re: slicing, mapping types, ellipsis etc.

2004-11-30 Thread Nick Coghlan
Kent Johnson wrote:
Maybe instead of referring to mappings it should say "The primary must 
implement __getitem__(), which is called with a value that is 
constructed from the slice list, as follows."
In the section you mention, 'mapping' is equivalent to 'has __getitem__ 
defined', and I'd be surprised if it's an isolated usage. Python actually has 
trouble distinguishing between sequences and mappings, as anyone who as tried to 
use the 'isMapping' API would know (the isMapping API uses much the same 
definition as the reference manual does - so all sequences show up as mappings, 
as they map indices and slices to objects).

Section 3 of the reference manual is actually more use for anyone developing 
custom types that override special methods. E.g. proper handling of slice 
objects is described here under container emulation:
http://www.python.org/dev/doc/devel/ref/sequence-types.html

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


Re: RELEASED Python 2.4 (final)

2004-11-30 Thread Dave Merrill
Used the packaged Windows (win2k) installs of Python and all components I
described. Not a C guy, no compiler, minimal knowledge about them.

Dave Merrill

"Anthony Baxter" wrote:
> > Newb question: Is it possible/recommended  to have multiple versions of
> > Python installed simultaneously? Earlier, I installed 2.4rc1, and a
number
> > of things in my 2.3.3 install stopped working. Are there known
techniques
> > for managing multiple versions?
>
> If you're building from source, use 'make altinstall' rather than
> 'make install'.
> This will install Python as $prefix/bin/python2.4, and leave the
> 'python' executable
> alone.


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


Re: comment out more than 1 line at once?

2004-11-30 Thread Jerry Sievers
Uwe Grauer <[EMAIL PROTECTED]> writes:

> Riko,
> 
> if you are using emacs, try C-c # to comment out a block of code.
> Unfortunally Uncomment is not bound to a key by default.
> Do a key-binding for it by yourself.

In Emacs, you can have the comment-region command do uncomment by
typing C-u first;

C-c #   comment region
C-u C-c #   uncomment region

>From the Emacs online help for plain comment-region'.  you are
probably invoking py-comment-region which is just a python tailored
version;

Comment or uncomment each line in the region.  With just C-u
prefix arg, uncomment each line in region.  Numeric prefix arg
ARG means use ARG comment characters.  If ARG is negative,
delete that many comment characters instead.  Comments are
terminated on each line, even for syntax in which newline does
not end the comment.  Blank lines do not get comments.

...Curiosly, I tried the numeric prefix arg to see it use 2 or more
comment chars or delete as many and I get 2x the number of the prefix
arg.

C-u 2 C-c # and I get;

def foo():

HTH


-- 
---
Jerry Sievers   305 854-3001 (home) WWW ECommerce Consultant
305 321-1144 (mobilehttp://www.JerrySievers.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


private attributes in __slots__ and pickle

2004-11-30 Thread i_hate
Hello,
I've just discovered the hard way that classes declaring private variables
(beginning with two underscore) can not be pickled ; double underscored
attributes are just not returned by __reduce__.

That's very annoying.

Objects should be serializable transparently so why such obstacles ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: private attributes in __slots__ and pickle

2004-11-30 Thread i_hate
[EMAIL PROTECTED] wrote:

> Hello,
> I've just discovered the hard way that classes declaring private variables
> (beginning with two underscore) can not be pickled ; double underscored

I meant "declaring private attributes in __slots__" ; sorry.

> attributes are just not returned by __reduce__.
> 
> That's very annoying.
> 
> Objects should be serializable transparently so why such obstacles ?

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


Re: Syntax for extracting multiple items from a dictionary

2004-11-30 Thread Leif K-Brooks
shark wrote:
row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken", "state" :
"Alaska"}
cols = ("city", "state")
Is there a best-practices way to ask for an object containing only the keys
named in cols out of row? In other words, to get this:
{"city" : "Hoboken", "state" : "Alaska"}
Why would you need to do that? There's nothing you can do to the second 
dictionary that you can't do to the first, so what's wrong with leaving 
the extra items in place?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Syntax for extracting multiple items from a dictionary

2004-11-30 Thread Roy Smith
In article <[EMAIL PROTECTED]>, "shark" <[EMAIL PROTECTED]> 
wrote:

> row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken", "state" :
> "Alaska"}
> cols = ("city", "state")
> 
> Is there a best-practices way to ask for an object containing only the keys
> named in cols out of row? In other words, to get this:
> {"city" : "Hoboken", "state" : "Alaska"}
> 
> Thanks,
> 
> shark

Just out of curiosity, why would you want to do that?  Are you trying to 
save on memory to store a lot of these things?  If so, I suspect you'd 
do even better (a few bytes per object) to store tuples of just the 
values, i.e. ("Hoboken", "Alaska"), and unpack them as you need them.

But, to answer your question, I don't know of any standard way to do 
what you want.  It's easy enough to write (a production version would 
probably want to catch KeyError's inside the for loop):

def getDictionarySlice (row, cols):
   slice = {}
   for key in cols:
  slice[key] = row[key]
   return slice

This won't work, but it would be kind of cool if it did:

def getOmnicientDictionarySlice (row, cols):
   for key not in cols:
  del row[key]

Hmmm.  Maybe there's an April Fools PEP in there somewhere :-)  
Actually, you could do:

def deleteUnwantedKeysInPlace (row, cols):
   for key in row.keys():
  if key not in cols:
 del row[key]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re[2]: weird behaviour of "0 in [] is False"

2004-11-30 Thread Laszlo Zsolt Nagy
>> (0 in l) is False
>>> True

This gives me the same exception.

>>> 0 in 1
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: iterable argument required

Did you really try these examples?


Best,

   Laci

mailto:[EMAIL PROTECTED]
web:http://designasign.biz


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


Re[3]: weird behaviour of "0 in [] is False"

2004-11-30 Thread Laszlo Zsolt Nagy
Tuesday, November 30, 2004, 3:15:27 PM, you wrote:
>>> (0 in l) is False
 True

> This gives me the same exception.

 0 in 1
> Traceback (most recent call last):
>   File "", line 1, in ?
> TypeError: iterable argument required

Sorry, It was 0 in l, not 0 in 1. :-)
My fault.

> Best,

>Laci

mailto:[EMAIL PROTECTED]
web:http://designasign.biz



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


Re: Syntax for extracting multiple items from a dictionary

2004-11-30 Thread Stefan Behnel

shark schrieb:
row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken", "state" :
"Alaska"}
cols = ("city", "state")
Is there a best-practices way to ask for an object containing only the keys
named in cols out of row? In other words, to get this:
{"city" : "Hoboken", "state" : "Alaska"}
Untested:
dict( (key,value) for (key,value) in row.iteritems() if key in cols )
Works in Py2.4
Stefan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Re[2]: weird behaviour of "0 in [] is False"

2004-11-30 Thread Richard Brodie

"Laszlo Zsolt Nagy" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]

> Did you really try these examples?

>>> l is 1
False


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


Re: slicing, mapping types, ellipsis etc.

2004-11-30 Thread Kent Johnson
Nick Coghlan wrote:
Kent Johnson wrote:
Maybe instead of referring to mappings it should say "The primary must 
implement __getitem__(), which is called with a value that is 
constructed from the slice list, as follows."

In the section you mention, 'mapping' is equivalent to 'has __getitem__ 
defined', and I'd be surprised if it's an isolated usage. Python 
actually has trouble distinguishing between sequences and mappings, as 
anyone who as tried to use the 'isMapping' API would know (the isMapping 
API uses much the same definition as the reference manual does - so all 
sequences show up as mappings, as they map indices and slices to objects).

Section 3 of the reference manual is actually more use for anyone 
developing custom types that override special methods. E.g. proper 
handling of slice objects is described here under container emulation:
http://www.python.org/dev/doc/devel/ref/sequence-types.html
I understand that the distinction between sequences and mappings is 
fuzzy, as both use __getitem__() for access. But the usage of 'mapping' 
in 5.3.3 is inconsistent with the section you refer to. That page says 
"It is also recommended that mappings provide the methods keys(), 
values(), items(), has_key(), get(), clear(), setdefault(), iterkeys(), 
itervalues(), iteritems(), pop(), popitem(), copy(), and update() 
behaving similar to those for Python's standard dictionary objects."

and under __getitem__(): "For *sequence* types, the accepted keys should 
be integers and slice objects."

I just think 5.3.3 is unnecessarily opaque. Particularly since the only 
built-in mapping (dict) doesn't even accept simple slices as indices.

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


Re: pre-PEP generic objects

2004-11-30 Thread Carlos Ribeiro
On Tue, 30 Nov 2004 22:30:21 +1000, Nick Coghlan <[EMAIL PROTECTED]> wrote:
> The proposed use cases sound more appropriate for a "named tuple" than any 
> sort
> of dictionary. (This may have been mentioned in previous discussions. I wasn't
> keeping track of those, though)

I agree with it. I was involved in that discussion, and got the the
point of listing a few desired features. As I am currently involved
into other project, I left it as it was, but I'll resume working as
soon as I can. I really think that both (generic objects and named
tuples) are slighly different but still very similar approaches to the
same problem, so some sort of "unification" of the efforts may be
interesting.

But there's something more important: while reading this document, and
some of the replies, it became clear that the main point is to
understand whether this proposed feature (in any possible
implementation) is in fact useful enough to deserve a place in the
standard library, and also if it represents a good coding style. With
some risk of being way too simplistic, it's something like this:

-- The people that is favorable to this implementation argue that one
should not be required to create a new class just to return a bunch of
results.

-- The people that is against it point out that, as soon as you start
returning multiple values, it's probable that you'll need to implement
a class anyway, so it's better off to do it sooner and forget generics
(or named tuples) entirely.

I see some parallels between this discussion and another one about
polymorphism. It's considered good Python practice to rely on
interfaces, or protocols, when designing the call signature of a
function or method. So if you receive an arbitrary object, you should
not check if it's a descendand of some abstract parent type; that's
just too rigid, and forces people to deal with complex multiple
inheritance stuff, and that's really not needed in Python. There is a
better way: just check if it exposes the desired interface, or
protocol. The adaptation framework (as described by PEP 246, and
extended by the PyProtocols package) is a nice implementation of this
concept.

A "generic" return object is just like this, but for a different
scenario: an adaptable return value, that doesn't enforce a class
signature when assigning the return value of a function or method.
It's perfectly symmetrical to the usage of interfaces on call. I think
that's a better, and much more powerful argument for the
implementation of a generic class, and also, for some supporting
machinery for it.

Extending this reasoning, generic return objects (implemented either
as dictionary based, or as named tuples) could be seen as "adaptable"
return values. Upon return, one could get  such a temporary structure
and assign its members into another, more complex class, that would
accept fields of the same name, but possibly include other fields and
extra functionality. For example: a function that returns a complex
time structure does not need to return a "time class". It may return a
generic, or named tuple, which is in turn can be assigned to an object
that exposes a 'compatible' assignment interface. This assignment can
be done by a method of the generic clas itself, according either to
the names of the member of the generics, or the order of the tuple,
depending on the scenario.

For now, that's all that I have to contribute into this discussion.
There's also a lot of stuff in the c.l.py archives regarding named
tuples and also generics that is surely worth checking.

-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: [EMAIL PROTECTED]
mail: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: py.test anyone?

2004-11-30 Thread holger krekel
Hi Stephen, 

[Stephen Boulet Mon, Nov 22, 2004 at 11:14:57AM -0600]
> Have people been using py.test? I was hoping to try it out but was 
> running into subversion problems (behind a corporate firewall, though 
> there is a windows registry hack for that which didn't work for me).

you may try to use the svn apache instance at 8080 aka 

svn co http://codespeak.net:8080/svn/py/dist distpy 

Also please note that 'py.test' has not been released yet. 
I plan to release it beginning of next year after it 
received some more development and a big real-life integration into 
the PyPy project. Nevertheless, there is quite some documentation 
under the 'py.test' link found here: 

http://codespeak.net/py/current/doc/ 

there also is a "getting started" link which now incorporates 
the above ":8080" suggestion. 

have fun, 

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


Re: Problem with tkinter mainloop

2004-11-30 Thread k2riddim
Many thanks, You're right this wasn't my code, this was just what I
can remember, because my application is at home, and I'm at work.
Be sure I'll follow your advices concerning posting rules in this
group !

Eric Brunel <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
> k2riddim wrote:
> > Hello,
> > I'm a beginner with Python and Tkinter development.
> > My application parse links in an html file. And I use Tkinter to
> > implement a GUI. This GUI has a button to launch the parse treatment,
> > and a status bar to show the state of the treatment.
> > I know that because of the mainloop, my tkinter application freeze
> > while my treatment isn't finished. That's why my status bar doesn't
> > update herself in real time.
> > I wanted to use the after or the after_idle function, but I don't
> > really understand why it doesn't work.
> 
> after and after_idle won't help you: the action you register in these methods 
> are called only when the main loop gets back the control, and your problem is 
> precisely that the main loop does not get it...
> 
> The method you're probably looking for is update_idletasks: it updates the 
> display without getting any user event. There's another method called update, 
> but this one does process user events, so it may call some of your code if 
> such 
> an event is pending. This is usually not what you want to do, except in some 
> very rare cases.
> 
> Here is how it may look like in your code, along with a few remarks on your 
> code:
> 
> > 
> > My apps is build approximately like that :
> > 
> > ---Gui.py---
> > class Gui(Frame):
> 
> Why do you inherit from Frame? A Tkinter Frame is a generic container widget; 
> this is not a window. IMHO, you'd better inherit from Tk for your main window 
> or 
> from Toplevel for other windows. You'd also get better control on the actual 
> window, since some of the methods available on Tk and Toplevel are not 
> available 
> on other widgets (e.g. geometry or protocol)
> 
> > def __init__(self):
> > ...
> > def launchTreatment(self):
> >b = Treatment()
> >self.after(b.treatment.parse)
> 
> This cannot be your code; the after methods takes two parameters: the number 
> of 
> milliseconds to wait before the action will be called and the action itself. 
> You 
> only provide the action here. But again, the after method won't help you to 
> get 
> what you want...
> 
> > 
> > ---Treatment.py---
> > class Treatment():
> > def __init__(self):
> > ...
> > def parse(self):
> >...
> >GUIinstance.status.set("state 1")
> 
> This is where the GUIinstance.update_idletasks() should go.
> 
> >...
> >GUIinstance.status.set("state 2")
> 
> Another GUIinstance.update_idletasks() here.
> 
> > 
> > 
> > ---Main.py---
> > #instanciation of classes
> > GUIinstance = Gui
> 
> Again, this cannot be your code, since you do not instantiate the class here. 
> The correct line should be:
> 
> GUIinstance = Gui()
> 
> It is usually far better to post a working example demonstrating the problem 
> you 
> have instead of just extracting a few lines of your whole code. This will 
> help 
> people who are willing to help to understand exactly what is going on.
> 
> HTH
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANNOUNCE: Ice 2.0 released

2004-11-30 Thread Anand Hariharan
Marc Laukien <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
> > I'm sure this is a wonderful thing, but your announcement gives absolutely
> > no clue as to what Ice is or what it is used for.
> > 
> > Please include an executive summary when you make an announcement like
> > this.
> 
> Sorry for the omission. Please see the summary below:
> 
(...)
> 
> Ice is free software, available with full source, and released under the 
> terms of the GNU General Public License (GPL). Commercial licenses are 
> available for customers who wish to use Ice for closed-source software."
> 

Interesting to see this blend of GPL and an alternative for
closed-source software.

Not totally unrelated, I saw this in your web-site (Ice vs CORBA
page):

No "Design by Committee" 
Ice was designed by a small group of dedicated and highly experienced
people.


Am interested to know, what "percentage" (*) of the code in your CVS
repository has been contributed by people other than the group
mentioned in the quote above?  Obviously, you do not allow anonymous
CVS write access.  Perhaps, one wishing to improve Ice (a freedom
granted by GPL) and who does not work for ZeroC has to mail his/her
improvements to your maintainers?

(*):  Percentage is a very nebulous term, I know.  For purposes of
answering the question, maybe you could resort to the
not-highly-meaningful number of LOC, and perhaps a word or two about
how Ice benefited from it.

- Anand

PS:  Please feel free to set FU-Ts as appropriate.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Protecting Python source

2004-11-30 Thread Gustavo Córdova Avila
Peter Maas wrote:
Grant Edwards schrieb:
On 2004-11-29, Peter Maas <[EMAIL PROTECTED]> wrote:
If the "reverse engineering" argument boils down to "protecting source
doesn't make sense" then why does Microsoft try so hard to  protect
its sources?
To avoid embarassment.
:) This cannot be the whole truth otherwise they wouldn't release
embarrasing binaries.
BWAAHHAHAHA!!!
Damn you!! Coke is so hard to clean off a keyboard!!
Good laugh, thankyou so much :-D
--
Gustavo CÃrdova Avila <[EMAIL PROTECTED]> 

*Tel:* +52 (81) 8130-1919 ext. 127
Integraciones del Norte, S.A. de C.V.
Padua #6047, Colonia SatÃlite Acueducto
Monterrey, Nuevo LeÃn, MÃxico.
--
http://mail.python.org/mailman/listinfo/python-list


Re: comment out more than 1 line at once?

2004-11-30 Thread Gustavo Córdova Avila
Riko Wichmann wrote:
Dear all,
is there a way in Python to comment out blocks of code without putting 
a # in front of each line? Somethings like C's

/*
block of code here is commented out
*/
Thanks,
Riko
I haven't seen the "other" way to block-comment multiple
lines of code: triple-quoted strings.
Strings which are unassigned in a source file are dropped
by the compiler, so they don't make it to the execution
stage; they're nice that way.
--
Gustavo Córdova Avila <[EMAIL PROTECTED]> 

*Tel:* +52 (81) 8130-1919 ext. 127
Integraciones del Norte, S.A. de C.V.
Padua #6047, Colonia Satélite Acueducto
Monterrey, Nuevo León, México.
--
http://mail.python.org/mailman/listinfo/python-list


From xemacs-beta mailing list

2004-11-30 Thread Skip Montanaro

Stephen Turnbull had this to say to a correspondent on the xemacs-beta
mailing list this morning.  I think it would be just as accurate if you
replaced "XEmacs" with "Python".

Many of the things you request are prima facie reasonable, and
we'll certainly consider them in the light of what they would
cost to implement.  But I rather suspect that your frustration
level would drop considerably if you'd stop trying to Kung Fu
XEmacs into submission, and try going with the flow,
aikido-style.

less-tae-bo-more-tai-chi-ly, y'rs,

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


Re: Numeric: 'where' function conditions

2004-11-30 Thread Jorl Shefner
In article <[EMAIL PROTECTED]>, Robert Kern <[EMAIL PROTECTED]> 
wrote:

> 
> Right. "3 < data" creates an array of 0s and 1s where the condition is 
> false and true, respectively. You don't need where() at all.
> 
> Try
> 
> mask = logical_and(3 < data, data <= 7)

Great.  That's exactly what I needed.  Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RELEASED Python 2.4 (final)

2004-11-30 Thread Harry George
"Dave Merrill" <[EMAIL PROTECTED]> writes:

> Newb question: Is it possible/recommended  to have multiple versions of
> Python installed simultaneously? Earlier, I installed 2.4rc1, and a number
> of things in my 2.3.3 install stopped working. Are there known techniques
> for managing multiple versions?
> 
> Thanks,
> 
> Dave Merrill
> 
> 

I can only speak for *NIX systems; don't know about MS Win** systems.
The quick answer is "Yes, it can be done".

1. Build and install as 
  make altinstall

This installs, e.g.:
  /usr/local/
  bin/
python2.3
  lib/
python2.3
  

It does NOT also make an entry at /usr/local/bin/python.  Thus any
scripts which call for "python" or "/usr/bin/env python" get the
default version.

2. Make a wrapper script, e.g. /usr/local/bin/py23:
  unset PYTHONHOME PYTHONPATH
  /usr/local/bin/python2.3 "$@"

3. Use "py23" to build site-packages.  Since you need to do this
repeatedly, it is best to save the build scripts on a python-version
basis.  E.g., a "go23" script.  Inside the scripts, use "py23" as
appropriate wherever you would have used "python".  e.g.:

  
  export PKGVER=Numeric-23.0
  ln -s ../${PKGVER}.tar.gz .
  gzip -cd  ${PKGVER}.tar.gz | gtar xvf -
  cd  ${PKGVER}

  py23 setup.py build
  py23 setup.py install
  cd ..
  

4. When another python version shows up, copy the go23 to go24, edit
it for py23-->py24, and start building.  Use either version at the
commmand line or in other scripts via py23 or py24.  NOTE: In cgi's,
give the full path, e.g.:

  #!/usr/local/bin/python2.3


-- 
Harry George
[EMAIL PROTECTED] 6-6M21 BCA CompArch Design Engineering
Phone: (425) 294-4718
-- 
http://mail.python.org/mailman/listinfo/python-list


SOAPpy/ZSI/Twisted SOAP over stdin/stdout?

2004-11-30 Thread Harry George
Normally the SOAP Servers are designed to take control of a port and
run their own sockets via inheritance from SocktServer.

But under inetd and xinetd, the port is controlled elsewhere and the
service just gets the stdin/stdout. I need to configure (or tweak) one
of the SOAP servers to use that connection.

Has anyone done this with any of the above named SOAP servers?
Recommmendations or hints if I try it myself?




-- 
[EMAIL PROTECTED]
6-6M21 BCA CompArch Design Engineering
Phone: (425) 294-4718
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question on sorting

2004-11-30 Thread Eddie Corns
wes weston <[EMAIL PROTECTED]> writes:

>Lad wrote:
>> Hi,
>> I have a file of records of 4 fields each.
>> Each field is separated by a semicolon. That is
>> 
>> Filed1;Ffield2;Field3;Field4
>> 
>> But there may be also empty records such as
>> 
>> (only semicolons).
>> 
>> For sorting I used
>> #
>> lines = file('Config.txt').readlines()# a file I want to sort
>> lines.sort()
>> ff=open('ConfigSorted.txt','w')# sorted file
>> ff.writelines(lines)
>> ff.close()
>> ###
>> It was sorted but empty records were first. I need them to be last(at
>> the end of the file). How can I do that?
>> 
>> Thanks for help
>> Lad

>Lad,
>The sort call can have a function name as an arg. You
>could do:

>def mycompare(s1,s2):
>#return -1 to put s1's at front; 1 to put s1's at back; 0 for a tie
>#if s1=="" and s2<>"": return 1

>lines.sort(mycompare)

I can't help feeling that the OP might have really wanted to be sorting on
individual fields rather than whole lines.  In which case I would think of
doing a line.split(';') on each line before sorting.  It would still need
either to use a function to make empty fields go later or alternatively use
DSU (google!) and convert '' to say '~' and back again. This also solves the
problem of what to expect when only some of the fields are blank rather than
all of them.

Eddie

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


Re: weird behaviour of "0 in [] is False"

2004-11-30 Thread Paul Robson
Sylvain Thenault wrote:

 l = []
 0 in (l is False)

(l is False) is not a tuple or list, it's a boolean value.

> Traceback (most recent call last):
> File "", line 1, in ?
> TypeError: iterable argument required
 (0 in l) is False
> True

0 in l is False becuase l is empty, so it's False is False which is true,
(except in Intercal probably and Visual C++)

 0 in l is False
> False

l is False is False because l is not the value false though it has a false
value (err.)

Okay. 

l != False because it's not the displayed value false

but if not l would evaluated to true because [] is a false equivalent.

0 in False  okay this should be an error . something to do with
the equivalence confusion of what False is ?



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


RE: python API wrapper for C++ API

2004-11-30 Thread Mark Doberenz
Thanks Josiah and everyone else who's replied to this already.

I'm taking a look at the web site Fredrik posted and I think it's going
to help me a lot.

I think I only need to be able to call C++ from Python.  The main thing
I'm confused about is how to make it so the Python program will directly
manipulate objects in the 3D program.

My brother has used Jython and he said in there, the Python Interpreter
is an object and you can bind it to an object.  I'm not sure how this
would happen in C++ though.

Thanks,
Mark

-Original Message-
From: Josiah Carlson [mailto:[EMAIL PROTECTED] 
Sent: Tuesday, November 30, 2004 1:59 AM
To: Mark Doberenz; [EMAIL PROTECTED]
Subject: Re: python API wrapper for C++ API


"Mark Doberenz" <[EMAIL PROTECTED]> wrote:
> I'm fairly new at Python, but I've got a project I really want to do.
>  
> I'm working with a real-time 3D program called Deep Creator, and it 
> has a C++ API written for it.  I'm wondering what it would take to 
> create a Python wrapper that would allow me to write Python programs 
> that would call the C++ API.
>  
> The main issue I'm running into is that I need to create a DLL that I 
> load as a plugin into Deep Creator.  I then will specify a python 
> program inside Deep Creator that I want to run, and the DLL plugin 
> will be the link between the python program and Deep Creator.
>  
> I'd really appreciate any ideas or issues that people see with this 
> set up.

The first thing you need to decide is whether you want to call C++ from
Python, Python from C++, both, or whether you want to embed a Python
interpreter inside your application.

The standard places to look for this kind of thing are ctypes, SWIG, and
Boost.Python.

 - Josiah

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


Struggling with struct.unpack() and "p" format specifier

2004-11-30 Thread Geoffrey
Hope someone can help.
I am trying to read data from a file binary file and then unpack the
data into python variables.  Some of the data is store like this;

xbuffer: '\x00\x00\xb9\x02\x13EXCLUDE_CREDIT_CARD'
# the above was printed using repr(xbuffer).  
# Note that int(0x13) = 19 which is exactly the length of the visible
text
#

In the code I have the following statement;
x = st.unpack('>xxBBp',xbuffer)

This throws out the following error;

x = st.unpack('>xxBBp',xbuffer)
error: unpack str size does not match format

As I read the documentation the "p" format string seems to address
this situation, where the number bytes of the string to read is the
first byte of the stored value but I keep getting this error.

Am I missing something ?
Can the "p" format character be used to unpack this type of data ?

As I mentioned, I can parse the string and read it with multiple
statements, I am just looking for a more efficient solution.

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


Re: SOAPpy/ZSI/Twisted SOAP over stdin/stdout?

2004-11-30 Thread Jp Calderone
On Tue, 30 Nov 2004 14:25:50 GMT, Harry George <[EMAIL PROTECTED]> wrote:
>Normally the SOAP Servers are designed to take control of a port and
> run their own sockets via inheritance from SocktServer.
> 
> But under inetd and xinetd, the port is controlled elsewhere and the
> service just gets the stdin/stdout. I need to configure (or tweak) one
> of the SOAP servers to use that connection.
> 
> Has anyone done this with any of the above named SOAP servers?
> Recommmendations or hints if I try it myself?
> 

  Twisted can run any protocol over stdio.

  Check out

http://twistedmatrix.com/documents/current/examples/stdin.py

  and

http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python

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


module imports and memory usage

2004-11-30 Thread Brad Tilley
When memory usage is a concern, is it better to do:
from X import Y
or
import X
Also, is there a way to load and unload modules as they are needed. I 
have some scripts that sleep for extended periods during a while loop 
and I need to be as memory friendly as possible. I can post a detailed 
script that currently uses ~ 10MB of memory if anyone is interested.

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


Re: Protecting Python source

2004-11-30 Thread Peter Hansen
Gustavo CÃrdova Avila wrote:
Peter Maas wrote:
Grant Edwards schrieb:
On 2004-11-29, Peter Maas <[EMAIL PROTECTED]> wrote:
If the "reverse engineering" argument boils down to "protecting source
doesn't make sense" then why does Microsoft try so hard to  protect
its sources?

To avoid embarassment.

:) This cannot be the whole truth otherwise they wouldn't release
embarrasing binaries.
BWAAHHAHAHA!!!
Damn you!! Coke is so hard to clean off a keyboard!!
Yeah, I hate the way the powder builds up between the keys.
Oh.
You meant the _drink_...
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Get Special Folders (ie Desktop location)

2004-11-30 Thread Peter Hansen
Colin Steadman wrote:
I'm just starting out writing Python scripts (in PSP), and need to
find the location of Windows special folders such as 'My Documents'
and 'Desktop' so that I can save files in the right place.  Is there
any method I can use in Python to get these?
If I were doing this in VBScript it'd be:
  DimWSHShell
  SetWSHShell = WScript.CreateObject("WScript.Shell")
  msgbox WSHShell.SpecialFolders("Desktop")
Use COM:
>>> from win32com.client import Dispatch
>>> w = Dispatch('WScript.Shell')
>>> w.SpecialFolders('Desktop')
u'C:\\Documents and Settings\\Colin\\Desktop'
-Peter
P.S.: Yes, I edited the result to look like yours might. ;-)
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >