Re: Python cleanup on exit

2006-03-10 Thread Fredrik Lundh
Jacob Kroon wrote:

> I'm working on a library written in C using GObject, which i
> provide python bindings for using pygtk. When I checked the
> library for memory leaks using valgrind, I noticed that none
> of the objects I created in the script (that is they are global in
> the script) were deleted on exit. After some googling I came
> to the conslusion that the python interpreter doesn't "cleanup"
> after itself on exit, because of shutdown performance.
>
> This means that if I want to check the library for mem leaks I have
> to either manually "del myobject1, delmyobject2 ..." at the end
> of the scripts, or make sure that all objects get created in a
> function scope, so that python will delete them for me when
> the interpreter exits the scope.

are the objects persistent on a system-wide level ?

if not, what's the problem ?  the operating system will clean them all
out much faster than you can do it yourself.

(the usual way to look for true leaks is to run the relevant code in a
loop.  stuff that's left for the operating system to throw away very
seldom qualifies as "leaks").





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


Re: File Permissions

2006-03-10 Thread Fredrik Lundh
"VJ" wrote:

> I need to get the user permission of a file using python. I was trying
> the following code which i found on google grups
>
>  st = os.stat(myfile)
> mode = st[stat.ST_MODE]
> if mode & stat.ST_IREAD:
> print "readable"
> if mode & stat.ST_IWRITE:
> print "writable"
> if mode & stat.ST_IEXEC:
> print "executable"
>
> I am getting a error saying
>
> " Traceback (most recent call last):
>   File "./test.py", line 23, in ?
> if mode & stat.ST_IREAD:
> AttributeError: 'module' object has no attribute 'ST_IREAD' "
>
> any idea how to resolve this error ??

fix your spelling:

>>> help(stat)
Help on module stat:
...

S_IREAD = 256
S_IRGRP = 32
S_IROTH = 4
S_IRUSR = 256
...

> Basically i want to write into a file .If the permissions are not there
> then print a error message.
> How do i achive this ???

that's an entirely different thing: if you want open a file and have that
operation fail if the file doesn't have the right permissions, open the file
and deal with any error you get:

try:
f = open(filename, mode)
except IOError, v:
... cannot open the file ...

or

try:
f = open(filename, mode)
except IOError, v:
import errno
if v.errno == errno.EPERM:
... wrong permissions ...
else:
raise # some other error; propagate

(note that there's nothing that guarantees that the permissions won't
change between a stat and a subsequent open, so the "look before you
leap" approach doesn't really work for operations against the file system)





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


Re: Cheese Shop: some history for the new-comers

2006-03-10 Thread Sybren Stuvel
richard enlightened us with:
> Rejoice! No more confusing conversations with PyPy developers!

Thanks for sharing that. I always wondered where the name came from :)

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: API/C memory mananegemnt problem

2006-03-10 Thread plahey
Sorry for responding to my own post.

I think I understand the original statement now.  What you are really
saying is that there is a pool of Python float objects (which can, at
different times, wrap different values) which can grow but never
decrease in size.  So the memory held by this pool is dictated by the
maximum number of floats that have ever been simultaneously active
(accessible).

The same goes for integers.  All the more reason to avoid range(.) and
use xrange(.).

So is this correct?

Thanks!

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


Re: Pythong CGI scrips on Windows Server 2003

2006-03-10 Thread Tim Roberts
Hugh Beyer <[EMAIL PROTECTED]> wrote:
>
>We are moving to a new server running Windows Server 2003 from existing 
>servers runing Windows Server 2002 and IIS is giving us fits.

Do you mean Windows 2000 Server?

My experience with IIS has been universally bad.  In each and every case, I
found it much more productive to disable IIS and install the Win32 version
of Apache.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: put multiple condition in if statement

2006-03-10 Thread Steven D'Aprano
On Fri, 10 Mar 2006 21:47:33 -0800, Alex Martelli wrote:

> <[EMAIL PROTECTED]> wrote:
> 
>> Hi,
>> 
>> How can I put multiple condition in if statement?
>> 
>> I try this, but I can't get that to work.
>> 
>> if ( (str != " ") && (str != "") ):
> 
> Why would you WANT to conjoin two instances of the SAME check...?!

No, the first is checking for str equal to a space character, the second
for the empty string. You need to get those glasses checked *grin* 


Note to the original poster: the more "pythonic" way of doing this check
will be:

if s and s.strip():
# do something with non-empty s
else:
# s is either empty or all whitespace

Don't use "str" as a variable name, as it will over-ride the built-in type
str. This will eventually cause you problems, when you try something like
this:

>>> str(5)
'5'
>>> str = "Hello world"  # shadow the built-in
>>> str(5)
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: 'str' object is not callable



-- 
Steven.

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


Re: API/C memory mananegemnt problem

2006-03-10 Thread plahey
I have not looked into C programming and Python so I probably don't
understand the issues here but the above statement sounds very
troubling.

Does this mean that any integer or float created anywhere at anytime in
a (pure) python program will be stored away for all time (as long as
the program is running)?

If the above is true my initial reaction is to recoil in horror...

Say it ain't so Joe!

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


Re: put multiple condition in if statement

2006-03-10 Thread Steven D'Aprano
On Fri, 10 Mar 2006 21:12:57 -0800, Allerdyce.John wrote:

> Hi,
> 
> How can I put multiple condition in if statement?
> 
> I try this, but I can't get that to work.
> 
> if ( (str != " ") && (str != "") ):


>>> if ( (str != " ") && (str != "") ):
  File "", line 1
if ( (str != " ") && (str != "") ):
   ^
SyntaxError: invalid syntax

Hmmm... it looks like && is a syntax error in Python. That's probably
because Python isn't C or Java or whatever language you're trying to
program in :-)

Python has operators and, or, not that will do what you are trying to do.

You may want to read these first:

http://docs.python.org/ref/bitwise.html
http://docs.python.org/ref/Booleans.html



-- 
Steven.

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


Re: Python and C

2006-03-10 Thread Terry Reedy

"P Boy" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>> Has anyone yet written a program to grab C struct declaration from the 
>> .h
>> to produce code like
>>
>> # Overlay configuration
>> class OverlayStoreConfig(ctypes.Structure):
>> _fields_ = [('FormatVersion',   ctypes.c_ulong),
>> ('VolumeSize',  ctypes.c_longlong),
etc
>
> http://starship.python.net/crew/theller/ctypes/codegen.html says it can
> be done. However, it requires MSVC 7.1 and I have not yet install it
> since I already have MSVC (6,7,8) on my PC.

Or vc6.  Neither of which most people have, especially those not using Swig 
because they don't do C.  Ok, we need program entirely in Python.  Possible 
exercise for someone.

> My header file is relatively small. The manual translation exercise
> also allowed me to understand more details about ctypes.

Sure, the first time I would do such also.

tjr



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


python search path on the command prompt in windows

2006-03-10 Thread John Salerno
Is there a way for me to somehow specify that I want Python to search 
all subdirectories of a particular directory when I'm running or testing 
files from the command prompt?

For example, I have a folder in my C:\Python24 folder called myscripts\. 
At first I saved my scripts in there, since there weren't many, and any 
work I did from the command prompt I did from this directory (with the 
directory added to my PYTHONPATH variable). But after using py2exe and 
seeing how many extra files and directories it created, I started to 
realize that it would be silly to keep all my files in just one folder.

So I made two folders in my myscripts\ folder, one called mytimer\ and 
the other called switches\. Now, if I'm still working in the myscripts\ 
directory at the command prompt, is there a way for Python to 
automatically check into these directories for any files I might be 
trying to run?

If not, is there a better way to do this?

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


Cheese Shop: some history for the new-comers

2006-03-10 Thread richard
So I wrote PyPI back a couple of years ago. It was just a simple cgi script
and some distutils code. I needed to call it *something* and "Python
Package Index" seemed like a fairly obvious name. Unfortunately, it's also
quite a mouthful. A friend suggested "PyPI" as a good shorter name. He also
indicated that it should be pronounced "Pippy" but that never really caught
on (just a little too cutesy for most people, I suppose).

Fast-forward to PyCon 2005. PyPI sprinters in the same room as PyPy
sprinters. I think you may see where this is heading. Every now and then
someone would say "Pie Pie" too loudly in the room, and *all* heads (well,
except the Chandler folk and Brett Cannon). Something needed to be done. A
new name was needed.

For the 6 months or so following PyCon 2005 I called for new name
suggestions. Some of those are in my weblog. Some are in c.l.p archives.
There was *zero* consensus, or anything even closely resembling consensus.
So I did what people always do in this situation, I asked Barry Warsaw to
name. it. And he did, "Cheese Shop". I liked the name, so it was done. When
the new pydotorg machines went live last year, so too did the name
cheeseshop.python.org

Rejoice! No more confusing conversations with PyPy developers!


 Richard

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


Re: Speed of data structures in python

2006-03-10 Thread Steven D'Aprano
On Fri, 10 Mar 2006 21:06:27 -0600, Terry Hancock wrote:

> On Sat, 11 Mar 2006 13:12:30 +1100
> "Steven D'Aprano" <[EMAIL PROTECTED]> wrote:
>> On Fri, 10 Mar 2006 23:24:46 +1100, Dave wrote:
>> > Hi. I am learning PyOpenGL and I am working with a
>> > largish fixed scene   composed of several thousand
>> > GLtriangles. I plan to store the coords and   normals in
>> > a NumPy array.
>> > 
>> > Is this the fastest solution in python? 
> 
>> Optimization without measurement is at best a waste of
>> time and at worst counter-productive. Why don't you time
>> your code and see if it is fast enough?
>> 
>> See the timeit module, and the profiler.
> 
> Talk about knee-jerk reactions. ;-)

Yes, let's.

> It's a *3D animation* module -- of course it's going to be
> time-critical.  Sheesh.  Now *that* is stating the obvious.

Did I say it wasn't? I asked if the current solution is fast enough. If
the current solution is fast enough, then why waste time trying to speed
it up? Does the Original Poster think that PCs will get slower in the
future?


> The obvious solution is actually a list of tuples. 

But that's not the solution being asked about, nor did I suggest it.


> But
> it's very possible that that won't be fast enough, so the
> NumPy approach may be a significant speedup. I doubt you
> need more than that, though.

I didn't argue against the NumPy approach. I suggested that, instead of
*asking* if there was something faster, the O.P. should actually *try it*
and see if it is fast enough.

If you think that is bad advice, please tell us what you consider good
advice.



-- 
Steven.

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


Re: put multiple condition in if statement

2006-03-10 Thread Alex Martelli
<[EMAIL PROTECTED]> wrote:

> Hi,
> 
> How can I put multiple condition in if statement?
> 
> I try this, but I can't get that to work.
> 
> if ( (str != " ") && (str != "") ):

Why would you WANT to conjoin two instances of the SAME check...?!

Anyway, use 'and' -- there's no such thing as '&&' in the Python
language!


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


put multiple condition in if statement

2006-03-10 Thread Allerdyce . John
Hi,

How can I put multiple condition in if statement?

I try this, but I can't get that to work.

if ( (str != " ") && (str != "") ):

Any help is appreciated.

Thank you.

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


The Python multiple IDE Collaboration calls for coders

2006-03-10 Thread SPE - Stani's Python Editor
Dear Pythoneers,

Looking at IDE's I can have three observations:

1. For some reasons numerous users prefer to use an open source IDE.

2. For some reasons numerous python programmers like to develop an open
source IDE.

3. For some reasons the open source python IDE developers are not
collaborating at all.

The reasons for 1 or 2 are obvious, at least to me. Recently I have
been wondering about the reason for 3. (Probably a lot of python
programmers have wondered about this already for ages, but ok I might
be slow ;-) I came to the conclusion that there was *NO* reason.

As this was so clear, I started to invite all the authors of IDE's
personally to collaborate all together. I hope that I didn't forget
any, because there are so many. What is really nice, is that we feel
the same: we should work together and share as much as possible. We
don't want to waste our (often spare) time on reinventing wheels.
Almost all IDE's (except of two) are participating no matter if they
use Tkinter, wxPython, pyQT, Cocoa, pyGTK, ... (So this could open
doors for an ajax python editor, who knows. Any python web framework
like Django, Turbogears, ... interested in that?)

These projects are participating: NewEdit, scrIDE, Eric3, Leo IDE,
ActiveGrid, PIDA, drPython, pyDev, PyCrust, IPython, WinPdb debugger,
Extended Python Debugger, PyLint, Gaphor, Envisage, Dabo, SilverCity &
SPE.

It is not about unification, but about a little bit more collaboration.
There are always libraries to share, more as we might think.

In order to give the project shape I started building a (wiki based)
website in plone which together with a mailing list should give a good
platform for collaboration.  (You need to login to edit wiki's.) All
the developers are already invited, but everyone willing to code or
contribute (documentation, translation, artwork, plone website, ..) is
welcome.  If you work on open source project which might be of interest
(parsing, uml, framework, ...) please join or invite the projects which
you think should participate as well.

We will probably work in smaller teams on the various aspects of IDE's
and tools. If this project succeeds it could be a major win for the
Python community.

These are some useful links:

- homepage: http://pyxides.stani.be
- mail list: http://pyxides.stani.be/polls/mailing
- starting mail: http://pyxides.stani.be/wiki/StartingEmail
- developers reaction: http://pyxides.stani.be/wiki/AuthorsOfIDEsTools
- poll:
http://pyxides.stani.be/polls/20060310-firstfocus/PlonePopoll_results2

Stani

PS IDLE is the only one which didn't answer my invitation yet, but we'd
love them to be in the team as well. (Kurt?)

-- 
http://pythonide.stani.be

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


Re: creating an executable?

2006-03-10 Thread John Salerno
Larry Bates wrote:
> John Salerno wrote:
>> Well, now that I can time my laundry, I need to make it runnable. I
>> tried looking for info on the freeze module in the help file, but it
>> didn't seem to come up with much. According to the Python wiki, freeze
>> is for making executables for Unix.
>>
>> Can I make an executable with just the standard distribution, or do I
>> need a separate module?
>>
>> Thanks.
> 
> You didn't ask about an installer, but I thought I'd make the suggestion
> anyway.  The combination of py2exe and Inno Installer works EXTREMELY
> well for distributing software on Windows platform.  Use py2exe to
> create .exe and support files, use Inno to wrap it up into a neat single
> setup.exe file for distribution.
> 
> -Larry Bates

Thanks. That's definitely something I would ask about eventually, so 
I'll check that one out too!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: API/C memory mananegemnt problem

2006-03-10 Thread Tim Peters
[EMAIL PROTECTED]
> Hi everybody,
> I have a problem with Python/C API and memory management.
>
> I'm using
> Python 2.3.5 (#1, Jan  4 2006, 16:44:27)
> [GCC 4.0.2 20050901 (prerelease) (SUSE Linux)] on linux2
>
> In my C-module I have a loop like this:
> ***
>
> int size=1000;
>
> output=(double *) calloc(size, sizeof(double));
>
> py_output=PyList_New(0);
>
> for(i=0; i   tmp=PyFloat_FromDouble(output[i]);
>   PyList_Append(py_output, tmp);
> }
>
> free(outout);
>
> return py_output;
>
> ***
>
> It returns to python module a (very large) list.
>
> Problem: when I delete the list in python module (with python del statement)
> not all memory is relased.
>
> It look like all 1000 tmp PyFloat allocated in C code
> remain stored in memory.
>
> Somebody can help me?

As Fredrik noted, your refcounting is off and you need a great deal of
error-checking code.

However, none of that will help your underlying problem:  CPython
floats are allocated in a special free list dedicated to floats, and
that free list is both immortal and unbounded in size.  Once Python
has allocated memory to hold a Python float, that memory is never
released.  BTW, Python has another, distinct immortal and unbounded
free list dedicated to holding storage for int objects.

There's nothing you can do about that.  It may be possible for you to
use an array.array to hold "unboxed" floats directly; that depends on
details of your app.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: capturing stdout from lynx..

2006-03-10 Thread Enigma Curry
Does this do what you want?

import os
filename = "test.html"
cmd = os.popen("lynx -dump %s" % filename)
output = cmd.read()
cmd.close()
print output

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


Re: How To Request Delivery Receipts On Emails

2006-03-10 Thread Gregory Piñero
Thanks for the help, guys.  This project was put on hold so I wasn't
able to try out any of the advice yet.  I'll let you know when I do.

-Greg


On 3/8/06, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Wed, 8 Mar 2006 12:52:04 -0500, "Gregory Piñero"
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
> > Hi Guys,
> >
> > Does anyone know how to program a Python script to send out emails
> > with a request delivery receipt?  Is it something I can build into the
> > email message via the mime stuff?
> >
> http://www.faqs.org/rfcs/rfc1891.html
> http://www.faqs.org/rfcs/rfc2821.html
> http://www.faqs.org/rfcs/rfc2822.html
>
> I'm not sure if there IS a single method yet. Eudora has/had secret
> ini parameters for "old style return receipt"; Outlook/Exchange have
> both "when delivered" and "when read" receipts.
>
> >From Eudora help:
> Request a Return Receipt
>
> (Sponsored and Paid modes only)
> You can request that your recipients notify you when they have seen your
> message. To do this, click the Return Receipt button in the message
> toolbar.
> When your recipients open the message and then close it, a dialog box
> appears asking them to create a notification message now, later, or
> never (if you send yourself a copy of the message, you will see the
> notification request). If a recipient chooses to create a notification
> message, it is sent to you and tells you when the recipient displayed
> your message.
>
> If you receive a request for notification, click Now to queue the
> notification message in your Out mailbox: it will be sent the next time
> queued messages are sent. Click Later to close the message without
> sending a notification or click Cancel to dismiss the notification
> request from the screen while the return receipt message is open;
> however, each time you open the message and then close it (or if you try
> to delete it), the notification request will appear until you click
> either Now or Never. Click Never to cancel the notification request
> without ever sending a notification message.
>
> The Return Receipt options may work differently than described,
> depending on your recipients' email software.
>
>
> Return Receipt
>
> If this is on, your recipients receive a request to notify you that they
> received the message.
> This function does not work in all cases, depending on the email
> application your recipients are using.
> --
>  > == <
>  >   [EMAIL PROTECTED]  | Wulfraed  Dennis Lee Bieber  KD6MOG <
>  >  [EMAIL PROTECTED] |   Bestiaria Support Staff   <
>  > == <
>  >   Home Page: <
>  >Overflow Page: <
> --
> http://mail.python.org/mailman/listinfo/python-list
>


--
Gregory Piñero
Chief Innovation Officer
Blended Technologies
(www.blendedtechnologies.com)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beautiful soup library question

2006-03-10 Thread Enigma Curry
Here's how I print each line after the 's:

import BeautifulSoup as Soup
page=open("test.html").read()
soup=Soup.BeautifulSoup(page)
for br in soup.fetch('br'):
print br.next

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


capturing stdout from lynx..

2006-03-10 Thread [EMAIL PROTECTED]
i have a huge database that contains large amounts of html that i need
to translate to ascii..

i have tried using html2text.py:

http://www.aaronsw.com/2002/html2text/

but i could not figure out how to import it and use it as a library
without getting errors everywhere..

so i decided to try using lynx with the -dump switch..

it works great from the command line, but i am having trouble capturing
the output into a python variable..

the only way i have figured out how to do it is:

s = subprocess(args='/sw/bin/lynx',stdout=subprocess.PIPE)

but i can't figure out how to send it the "-dump" or the
 and retrieve the ouput..

any help would be appreciated..

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


Re: Python and C

2006-03-10 Thread P Boy
> Has anyone yet written a program to grab C struct declaration from the .h
> to produce code like
>
> # Overlay configuration
> class OverlayStoreConfig(ctypes.Structure):
> _fields_ = [('FormatVersion',   ctypes.c_ulong),
> ('VolumeSize',  ctypes.c_longlong),
> ('NumSegments', ctypes.c_ulong),
> ('FreeSegments',ctypes.c_ulong),
> ('SegmentSize', ctypes.c_ulong),
> ('MaxVolumes',  ctypes.c_ulong),
> ('NumVolumes',  ctypes.c_ulong),
> ('MaxLevels',   ctypes.c_ushort),
> ('VolumeDescArray', pVolumeDesc),
> ]
> ?

http://starship.python.net/crew/theller/ctypes/codegen.html says it can
be done. However, it requires MSVC 7.1 and I have not yet install it
since I already have MSVC (6,7,8) on my PC.

My header file is relatively small. The manual translation exercise
also allowed me to understand more details about ctypes.

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


Re: Performance impact of using decorators

2006-03-10 Thread Alex Martelli
vinjvinj <[EMAIL PROTECTED]> wrote:

> >>what exactly made you think that Python would be able to run your
> >>code *without* calling your function ?
> 
> I was hoping that when the compiler finds decorators with wrapers that
> have the same signature it can some how "magically" combine them into
> one function (which gets called at run time) and not have 5 nested
> function calls. That is similar to what I will have to do eventually.
> 
> Given python's dynamic nature, I'm sure there are reasons why this is
> not done.

Yep, you'll have to build new functions yourself if you need them:-(


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


Re: Performance impact of using decorators

2006-03-10 Thread Alex Martelli
Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
   ...
> begin()
> try:
>   pass
>   commit()
> finally:
>   if not comitted():
> rollback()

Feels like a natural for 2.5's 'with' statement -- as has been the case
for 2.3 and 2.4, 2.5 won't have many language-level changes, but what
little there IS, is... wonderful!

with transaction():
   ...your code goes here...

is SO much better than the try/finally routine...!


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


Re: Why property works only for objects?

2006-03-10 Thread Alex Martelli
Michal Kwiatkowski <[EMAIL PROTECTED]> wrote:
   ...
> I'm trying to understand attributes lookups made by Python, having
> properties and special methods in mind. So far I've come up with kind of
>  reasoning I've coded below. I would appreciate any comments and
> suggestions.

First, let's forget legacy-style classes, existing only for backwards
compatibility, and focus on new-style ones exclusively -- never use
legacy classes if you can avoid that.

Descriptors come in two varieties: overriding and non-overriding. Both
kinds have a __get__ method (that's what makes them descriptors).
Overriding ones also have a __set__, non-overriding ones don't. (Until
pretty recently, the two kinds were known as data and non-data, but the
new terminology of overriding and non-overriding is much clearer).

I covered descriptors in one of my talks at Pycon '05 and elsewhere; you
can find just about all of my talks by starting at www.aleax.it (mostly
just PDF forms of the slides in my presentations). I cover them in quite
a central role in the forthcoming 2nd edition of Python in a Nutshell,
too. But, summarizing:

overriding descriptors are FIRST looked up in the class (class overrides
instance); non-overriding descriptors, first in the instance (class does
not override).  Functions are NON-overriding descriptors.

Special methods IMPLICITLY looked up by Python ALWAYS go to the class
ONLY -- adding an x.__getitem__ per-class attribute that happens to be
callable doesn't mean that attribute is gonna handle z=x[y] and the like
(in legacy-style classes the rule was different, but that led to a host
of complications that we're much better off without!).


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


Re: Why property works only for objects?

2006-03-10 Thread Alex Martelli
Michal Kwiatkowski <[EMAIL PROTECTED]> wrote:
   ...
> Let me understand it clearly. If I change __class__ of an object,
> existing attributes (so methods as well) of an object are still
> accessible the same way and don't change its values. Only resolution of
> attributes/methods not found in object is changed, as it uses new
> version of __class__ to lookup names. Is this right?

Attributes of the _instance_ are unchanged.  Anything that would
normally be looked up in the OLD __class__, such as methods, is gone:
which is why you normally set as the NEW __class__ some subclass of the
old one, so that nothing is really gone;-).


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


Re: Python and C

2006-03-10 Thread Alex Martelli
David Boddie <[EMAIL PROTECTED]> wrote:

> Alex Martelli wrote:
> > <[EMAIL PROTECTED]> wrote:
> 
> > C is the lowest, most fundamental level of extension, but there are many
> > other alternatives -- SWIG to wrap existing libraries, Boost or SCXX or
> > SIP to wrap specifically C++ with very different philosophies (template
> > heavy, minimal, Qt-based), pyrex (a Python "dialect" plus C-like
> > declarations to make it compilable to fast machine code), and others
> > yet.
> 
> It is a common misconception that SIP is only really used to wrap
> Qt-based libraries, though that may be its main use in many projects:
> 
>  "SIP is a tool that makes it very easy to create Python bindings
>   for C and C++ libraries. It was originally developed to create PyQt,
>   the Python bindings for the Qt toolkit, but can be used to create
>   bindings for any C or C++ library."

Ah, I see that SIP 4 is much better -- I was more experienced with 3.*,
which, what between lack of docs, no support for C, etc, was less
suitable for such a general role.  If SIP 4 can be installed quite
independently of Qt, then it's indeed grown to the stature you mention.


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


Re: Bidirectional communication over unix socket (named pipe)

2006-03-10 Thread J Rice
Thank you, that answers my question!  And it works fine with stream, so
I can do what I want as well.

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


Re: Speed of data structures in python

2006-03-10 Thread Terry Hancock
On Sat, 11 Mar 2006 13:12:30 +1100
"Steven D'Aprano" <[EMAIL PROTECTED]> wrote:
> On Fri, 10 Mar 2006 23:24:46 +1100, Dave wrote:
> > Hi. I am learning PyOpenGL and I am working with a
> > largish fixed scene   composed of several thousand
> > GLtriangles. I plan to store the coords and   normals in
> > a NumPy array.
> > 
> > Is this the fastest solution in python? 

> Optimization without measurement is at best a waste of
> time and at worst counter-productive. Why don't you time
> your code and see if it is fast enough?
> 
> See the timeit module, and the profiler.

Talk about knee-jerk reactions. ;-)

It's a *3D animation* module -- of course it's going to be
time-critical.  Sheesh.  Now *that* is stating the obvious.

The obvious solution is actually a list of tuples. But
it's very possible that that won't be fast enough, so the
NumPy approach may be a significant speedup. I doubt you
need more than that, though.

I think the real question is not going to be how fast your
code handles data, though, but rather how fast you can get
that data into PyOpenGL and back. So the real fastest format
is going to be "whatever PyOpenGL uses" -- so I'd look that
up.

For comparison, SDL uses "surfaces" to store 2D data, so
when programming in PyGame, your first step is to load every
image into a surface. Once there, display to the screen is
very very fast -- but moving from image to surface is
typically slow, no matter how spiffy your image format may
be internally.  I suspect something similar applies to
PyOpenGL.

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: Cheese Shop -> BSOL?

2006-03-10 Thread Tim Churches
Tim Churches wrote:
> Would it be possible to rename "Cheese Shop" as "Bright Side of Life"?
> 
> That's a cheery, upbeat name, there are overtones of commerce or filthy
> lucre, 

I meant "no overtones", mea culpa.

Tim C

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


Cheese Shop -> BSOL?

2006-03-10 Thread Tim Churches
Would it be possible to rename "Cheese Shop" as "Bright Side of Life"?

That's a cheery, upbeat name, there are overtones of commerce or filthy
lucre, it is a clear reference to one of the Monty Python crew's
greatest works, it can be easily abbreviated to BSOL (to avoid confusion
with BSL for blood sugar level, and to have some resonance with another
well-known Python acronym, BDFL), it is associated with a memorable
theme tune which, appropriately, reminds one to always look on the BSOL
(see http://www.geocities.com/fang_club/Bright_side_of_life.html for the
 lyrics), one can install an (ALOT)BSOL ringtone on your mobile (cell)
phone if one wishes like - see (or hear) for example
http://www.niksula.cs.hut.fi/~ajvaanan/p_80861/ , and it possesses a
certain irony just like the original Cheese Shop allusion.

So, BSOL instead of Cheese Shop? I am quite prepared to be crucified
(cheerfully) for this suggestion.

Tim C


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


Re: Speed of data structures in python

2006-03-10 Thread Steven D'Aprano
On Fri, 10 Mar 2006 23:24:46 +1100, Dave wrote:

> 
> Hi. I am learning PyOpenGL and I am working with a largish fixed scene  
> composed of several thousand GLtriangles. I plan to store the coords and  
> normals in a NumPy array.
> 
> Is this the fastest solution in python? would i be significantly better  
> off (timewise or otherwise) using some other data structure to hold this  
> information? no other data structure appears as convenient, but am i  
> loosing valuable time?
> 
> I am new to 3d programming so please feel free to state the obvious,  
> thanks.


Optimization without measurement is at best a waste of time and at worst
counter-productive. Why don't you time your code and see if it is fast
enough?

See the timeit module, and the profiler.


-- 
Steven.

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


Re: Silly import question (__file__ attribute)

2006-03-10 Thread Steven D'Aprano
On Thu, 09 Mar 2006 17:25:20 -0500, Jack Diederich wrote:

> It is a built-in module so it doesn't have a .so (dll) or .py file
> to mention.

Wouldn't it make sense for module.__file__ to be set to None rather than
completely missing in this case?


-- 
Steven.

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


Re: why use special config formats?

2006-03-10 Thread Steven D'Aprano
On Fri, 10 Mar 2006 09:08:36 -0800, tomerfiliba wrote:

> you can easily crash your web server (or make it non functional) if you
> pass an invalid port or host, or make it act weird by changing the
> timeouts or paths... so yeah, if the admin writes a config script that
> does os.system("rm -rf /"), well, too bad. 

Not if the code is being run on YOUR webserver and the config file is
being edited on some compromised PC in Romania.


> again -- the points are:
> * python is readable and easy to write config files with
> * usually admins change the configuration, and they have too much power
> anyway

So why do you want to give them MORE power?

> * if you worry about security/too much power, pickle your config

Huh? You think a competent sys admin can't learn enough Python to hack
your pickled file?

Binary configs only keep out legitimate users who don't have the time or
ability to learn how to hack the binary format. Black hats and power users
will break your binary format and hack them anyway.

> * if you need to edit your pickled config on a regular basis, serialize
> it with some other textual serializer (xml, etc).

But you forget the most important point of all:

* keep your data separate from your code.


> but inventing proprietary formats with unique syntaxes, and having to
> write and debug parsers for them -- that's stupid. a configuration is
> just a persistent state of your program. it shouldnt be any more
> complex than that.

Exactly. And that's why we have two or three common config file formats,
such as xml, ini files, etc. Pick one of them and stick to it.


-- 
Steven.

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


Re: Why property works only for objects?

2006-03-10 Thread Michal Kwiatkowski
Bruno Desthuilliers napisał(a):
>> Let me understand it clearly. If I change __class__ of an object,
>> existing attributes (so methods as well) of an object are still
>> accessible the same way and don't change its values. Only resolution of
>> attributes/methods not found in object is changed, as it uses new
>> version of __class__ to lookup names. Is this right?
> 
> Attributes, yes. Not methods. Methods are looked up in the class.

My experience shows exactly the opposite. Any attribute/method you try
to access is first looked up in object dictionary, then inside class
definition.

import types

class C(object):
def f(self):
print "old method f()"

obj = C()

def f(self):
print "new method f()"

obj.f = types.MethodType(f, C)

obj.f() # => "new method f()"

Since that works, intuitively for me would be to assign object's
descriptors like that:

obj.x = property(types.MethodType(lambda self: 42, C))

But I just get a property object. So, it seems descriptors have little
bit of magic, as they don't work identically for classes and objects.

The same goes for special methods and attributes (written as __*__). So
I cannot change __getattr__/__setattr__/__metaclass__ or any other
attribute that starts with __ for a single object. It's not so bad
except for situations were class of an object defines its own
__getattribute__ method, which takes control of an object from us. To
get/set any attribute of an object we must use object type methods:

class C(object):
def __getattribute__(self, name):
return 42

obj = C()

obj.a = 5

print obj.a # => 42
print object.__getattribute__(obj, 'a') # => 5

I gets even more strange when you try to modify, say __len__ or
__repr__. Docstring for object.__repr__ says:
"x.__repr__() <==> repr(x)" which doesn't seem to be always true:

class C(object):
def __repr__(self):
return "class repr"

obj = C()
obj.__repr__ = types.MethodType(lambda self: "instance repr", C)

print repr(obj) # => class repr
print obj.__repr__() # => instance repr

Maybe the manual should say "x.__class__.__repr__() <==> repr(x)" instead?

I'm trying to understand attributes lookups made by Python, having
properties and special methods in mind. So far I've come up with kind of
 reasoning I've coded below. I would appreciate any comments and
suggestions.

def lookup_name(obj, name):
get = lambda obj, name: object.__getattribute__(obj, name)
has = lambda obj, name: name in get(obj, '__dict__')

# assume C is a new style class
C = get(obj, '__class__')

# 1) use class' __getattribute__ method
try:
if has(C, '__getattribute__'):
return get(C, '__getattribute__')(obj, name)
except AttributeError: pass

# 2) lookup in object's dictionary
try:
if has(obj, name):
return get(obj, name)
except AttributeError: pass

# 3) lookup in classes
for c in obj.__class__.mro():
try:
if has(c, name):
desc = get(c, name)
# 3a) handle descriptors
try:
return get(desc, '__get__')(obj)
except: pass
# 3b) no descriptors -> use value
return desc
except AttributeError: pass

raise AttributeError, "Not found!"

mk
-- 
 . o .   >>  http://joker.linuxstuff.pl  <<
 . . o   It's easier to get forgiveness for being wrong
 o o o   than forgiveness for being right.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why no block comments in Python?

2006-03-10 Thread Terry Hancock
On Sat, 11 Mar 2006 10:23:56 +1100
"Steven D'Aprano" <[EMAIL PROTECTED]> wrote:

> On Thu, 09 Mar 2006 18:02:27 -0600, Terry Hancock wrote:
> 
> > On 9 Mar 2006 07:21:00 -0800
> > "msoulier" <[EMAIL PROTECTED]> wrote:
> >> > (and if you don't, you can quickly comment out
> >regions > > by putting them inside a triple-quoted
> >string.) > 
> >> Although that will use up memory, as opposed to a
> >comment.
> > 
> > Not really. Unless it is the first string in the block
> > (class, function, module), it won't be assigned to
> > anything, and will be immediately garbage-collected.
> > 
> > It may consume space in the pyc file, I'm not sure.
> 
> I don't believe this is true. Unassigned strings other
> than the doc string are not compiled into the code:

[bytecode analysis snipped]

Cool. I thought that was probably true, but didn't want
to guess.

Cheers,
Terry


-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: pyc file usage in a multi OS environment ( newbe question)

2006-03-10 Thread HajoEhlers
Thanks for clearifing the issue.

Hajo

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


Re: Why python doesn't use syntax like function(, , x) for default parameters?

2006-03-10 Thread Steven D'Aprano
On Fri, 10 Mar 2006 11:33:56 -0500, Terry Reedy wrote:

> Actually, I consider the unique calling pattern for x/range to be something 
> of a wart.  Learning this inconsistency was at least a minor problem.  It 
> is a rather extreme example of typing laziness beats purity.

Amazing. I consider it to be a rather extreme example of practicality
beating purity, an excellent example of interface design.

But I guess that's why Guido is BDFL. Well, that and the fact that he
invented Python *wink*


-- 
Steven.

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


Re: why use special config formats?

2006-03-10 Thread Steven D'Aprano
On Fri, 10 Mar 2006 06:48:03 -0800, tomerfiliba wrote:

> hey
> 
> i've been seeing lots of config-file-readers for python. be it
> ConfigObj (http://www.voidspace.org.uk/python/configobj.html) or the
> like. seems like a trend to me.
> i came to this conclusion a long time ago: YOU DON'T NEED CONFIG FILES
> FOR PYTHON.

Of course you do.

Sometimes you have to be able to parse and understand existing config
files that have come from somewhere else. If your task is "read and parse
a .ini file", insisting the user re-writes their ini file as Python code
isn't helpful.

Separating code from data is always a good idea. I hope I don't need to
explain why. So you want config files, the only question is, what format
should they be in?

Sometimes it can be useful, especially for quick and dirty apps, to use a
Python module as a config file. But that's not a good idea for production
level code where end users are expected to edit the data: 

# config.py
value = 2.5
colour = "blue"

The user edits value to 3.1, but accidentally puts in a typo "3,1".
Now when your application imports the config.py module, it silently
assigns the tuple (3, 1) to value, and your app dies an unpleasant death
somewhere a long way away. You have no idea why.

So you end up coding defensively to protect against user typos or
stupidity (and believe me, even if your users are technically minded IT
professionals, they will screw up your config files):

# config.py
import logger, sys
value = 2.5  # warning: value must be a float
colour = "blue"  # warning: colour must be one of "red", "blue", "green"
# warning: quotes are compulsory
try:
colour = colour.strip()
except AttributeError:
pass
if type(value) != float or value < 0.0:
logger.log("Value is %s" % value)
print >>sys.stderr("Bad value, using default")
value = 2.5
if colour not in ("blue", "red", "green"):
logger.log("Colour is %s" % value)
print >>sys.stderr("Bad colour, using default")
colour = "bleu" # oops, a bug 

and now your config file is code instead of data, and you expect your
users to hack code to change a default value. B--A--D idea.

Using a data config file means you can separate the user-editable data
from the code that verifies that it has sensible values. Your config file
becomes simple again:

# config.py
value = 2.5
colour = "blue"

and your users no longer have to wade through complex code to change a few
defaults, but you still have full flexibility to vet their data.

> why re-invent stuff and parse text by yourself, why the
> interpreter can do it for you? and anyway, i find this a very ugly
> format:
> http://www.voidspace.org.uk/python/configobj.html#the-config-file-format

You are joking right? Pulling our legs?

Here is the config file format, according to the link you supply:

# comment line
# comment line
keyword = value # inline comment

Here is the equivalent written in pure Python:

# comment line
# comment line
keyword = value # inline comment


Why is the first uglier than the second?



-- 
Steven.

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


Re: generators shared among threads

2006-03-10 Thread Bryan Olson
[EMAIL PROTECTED] wrote:
> You'll get the same result without the lock.  I'm not sure what this
> indicates.  It may show that the contention on the lock and the race
> condition on i aren't always problems.  It may show that generators, at
> least in CPython 2.4, provide thread safety for free.  It does seem to
> disprove my statement that, "the yield leaves the lock locked".
> 
> More than that, I don't know.  When threading is involved, different
> runs of the same code can yield different results.  Can we be sure that
> each thread starts where the last one left off?  Why wouldn't a thread
> just start where it had left off before?  Of course, this case would
> have the potential for problems that Alex talked about earlier.  Why
> would a generator object be any more reentrant than a function object?
> Because it has a gi_frame attribute?  Would generators be thread-safe
> only in CPython?

I have not found definitive answers in the Python doc. Both
generators and threads keep their own line-of-control, and
how they interact is not clear.


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


Re: Python Evangelism

2006-03-10 Thread Michael Tobis
The name isn't changing,  so it's a "make lemonade" situation.

What's the best use we can make of the name; how do we make it stick in
people's minds positively? How do we make a positive image out of it?

Shy tadpoles, by the way, ( http://python.org/images/python-logo.gif )
isn't it.

mt

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


Re: AES encryption

2006-03-10 Thread Bryan Olson
I wrote:
> Tuvas wrote:
> [...]
> 
>> I've tested my function with a thousand random texts, it
>> seems to return the same result as received every time.
> 
> 
> Unfortunately, the results seem incorrect, self-consistent
> as they may be. The following will call your code, and
> check the results against 3 popular test vectors.
> 
> --Bryan
> 
> 
> # Assert false if test fails
> 
> test_key = (
> 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6,
> 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c,
> 0x76, 0x2e, 0x71, 0x60, 0xf3, 0x8b, 0x4d, 0xa5,
> 0x6a, 0x78, 0x4d, 0x90, 0x45, 0x19, 0x0c, 0xfe)
> 
> test_plaintext = (
> 0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d,
> 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34)
> 
> expected = (
> (0x39, 0x25, 0x84, 0x1d, 0x02, 0xdc, 0x09, 0xfb,
> 0xdc, 0x11, 0x85, 0x97, 0x19, 0x6a, 0x0b, 0x32),
> 
> (0xf9, 0xfb, 0x29, 0xae, 0xfc, 0x38, 0x4a, 0x25,
> 0x03, 0x40, 0xd8, 0x33, 0xb8, 0x7e, 0xbc, 0x00),
> 
> (0x1a, 0x6e, 0x6c, 0x2c, 0x66, 0x2e, 0x7d, 0xa6,
> 0x50, 0x1f, 0xfb, 0x62, 0xbc, 0x9e, 0x93, 0xf3))
> 
> key_sizes = (16, 24, 32)
> plaintext = s2num(''.join([chr(c) for c in test_plaintext]))
> for i in range(len(key_sizes)):
> key_size = key_sizes[i]
> key = s2num(''.join([chr(c) for c in test_key[:key_size]]))
> expected = s2num(''.join([chr(c) for c in expected[i]]))
> ciphertext = encryptb(plaintext, key)
> assert ciphertext == expected
> deciphertext = decryptb(ciphertext, key)
> assert deciphertext == plaintext

Oops, introduced a bug by shadowing "expected". Make the for loop:

for i in range(len(key_sizes)):
 key_size = key_sizes[i]
 key = s2num(''.join([chr(c) for c in test_key[:key_size]]))
 expect = s2num(''.join([chr(c) for c in expected[i]]))
 ciphertext = encryptb(plaintext, key)
 assert ciphertext == expect
 deciphertext = decryptb(ciphertext, key)
 assert deciphertext == plaintext


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


Re: creating variable in root namespace from module

2006-03-10 Thread MakaMaka
Ok, but it seems to be working exactly as I need it to right now under
win32.  I'll try it on linux.  Can you suggest an alternative method?
Or suggest when this won't work?

Thanks,
-Justin

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


Re: How to best update remote compressed, encrypted archives incrementally?

2006-03-10 Thread Steven D'Aprano
On Fri, 10 Mar 2006 15:13:07 +0100, robert wrote:

> Hello,
> 
> I want to put (incrementally) changed/new files from a big file tree 
> "directly,compressed and password-only-encrypted" to a remote backup 
> server incrementally via FTP,SFTP or DAV  At best within a closed 
> algorithm inside Python without extra shell tools.

What do you mean by "closed algorithm"?

The only thing I can think of is you mean a secret algorithm, one which
nobody but yourself will know. So let's get this straight... you are
asking a public newsgroup dedicated to an open-source language for
somebody to tell you a secret algorithm that only you will know?

Please tell me I've misunderstood.


> (The method should work with any protocol which allows somehow read, 
> write & seek to a remote file.)
> On the server and the transmission line there should never be 
> unencrypted data.

Break the job into multiple pieces. Your task is:

- transmit information to the remote server;

Can you use SSH for that? SSH will use industrial strength encryption,
likely better than anything you can create.

- you want to update the files at the other end;

Sounds like a job for any number of already existing technologies, like
rsync (which, by the way, already uses ssh for the encrypted transmission
of data).



-- 
Steven.

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


Re: import and shared global variables

2006-03-10 Thread Diez B. Roggisch
> has to be imported by others.  Would a module global.py (defining glob 
> and imported by whoever needs it) be more pythonic?

I'd say yes.

> (I didn't want to do 
> that because I really want to resist the temptation of introducing 
> glob1, glob2, glob3...)

I miss seeing what that has to do with creating a special module.

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


Re: Performance impact of using decorators

2006-03-10 Thread Diez B. Roggisch
vinjvinj schrieb:
>>> That sounds like something for the templating engine, and _certainly_ not
>>> for a decorator that otherwise deals with transactions.
> 
> The actual code for the page layout is in a preppy template. But the
> calls to the template engine are made in the
> startTransactrionAndBuildPage decorator

Well, even if it would fit in a decorator - it certainly belongs to its 
_own_ decorator.


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


Re: lighter weight options to Python's logging package?

2006-03-10 Thread Diez B. Roggisch
> We've done a bit already.  I will see if there's more we can do.  Our use of
> the package is actually very simple.  All we do are log basic messages.  Our
> Formatter instance includes the time, level and message.  That's it.  We
> have no need for displaying exception info, don't do threads, don't mess
> with the file or module names, etc.  The only thing we do that isn't
> supported directly by the package is to use a compressing version of the
> RotatingFileHandler class.


In java's log4j a common idiom for logging is this:

if(logger.isDebugEnabled()) {
logger.debug(some_lengthy_calculation());
}


I never tried to employ that in python - but maybe it would help you 
too, as it certainly rids you of all unnecessary processing of messages 
that wouldn't make it anyway.

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


Re: Why python doesn't use syntax like function(, , x) for default parameters?

2006-03-10 Thread Steven D'Aprano
On Fri, 10 Mar 2006 12:06:57 +0300, Dmitry Anikin wrote:

> I mean, it's very convenient when default parameters
> can be in any position, like
> def a_func(x = 2, y = 1, z):
> ...
> (that defaults must go last is really a C++ quirk which
> is needed for overload resolution, isn't it?)

I'm confused... it looks to me like the defaults are *first*, not last, in
the above definition. We write from left to write in English, so normal
convention in English is that first -> last, not last <- first.


> and when calling, just omit parameter when you want to
> use defaults:
> a_func(, , 3)

Can you do this? another_func(,,,4)

That looks like bug-city to me. (Did I mean 4 to go in the fourth position
or fifth?)

In any case, given the way Python defaults work, the commas are
superfluous. There is no ambiguity:

def f(w, x, y=1, z=1):
pass

Positional arguments without defaults *must* go first, and must be
supplied:

f(5, 6) => w=5, x=6, y=1, z=1

Commas would be pointless: f(5, 6, , ) isn't needed, because the first
and second arguments are already assigned to the w and x arguments before
the first empty comma is spotted.

You can't do this: f(, , 5, 6) => w,x = default, y=5, z=6

because w and x don't have defaults.


> There are often situations when a function has independent
> parameters, all having reasonable defaults, and I want to
> provide just several of them. In fact, I can do it using
> keyword parameters, but it's rather long and you have to
> remember/lookup names of parameters.

And you think it is easier to remember the position of parameters rather
than their names?


-- 
Steven.

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


Re: counting number of (overlapping) occurances

2006-03-10 Thread Steven D'Aprano
On Thu, 09 Mar 2006 22:01:17 -0800, John wrote:

> Thanks a lot,
> 
> This works but is a bit slow, I guess I'll have to live with it.
> Any chance this could be sped up in python?

I don't know. What is it?

You should always quote enough of the previous poster's message to give
context. Messages sometimes go missing in Usenet, and people won't have
the foggiest idea what you are talking about.

-- 
Steven.

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


Re: Best way to have a for-loop index?

2006-03-10 Thread Steven D'Aprano
On Thu, 09 Mar 2006 20:22:34 -0500, Roy Smith wrote:

>> My question is, is there a better, cleaner, or easier way to get at the
>> element in a list AND the index of a loop than this?
>> 
>> TIA,
>> Andrew
> 
> The real question is *why* do you want the index?
> 
> If you're trying to iterate through list indicies, you're probably trying 
> to write C, C++, Fortran, Java, etc in Python.

That's a bit harsh, surely? Well-meaning, but still harsh, and untrue.
Wanting to walk through a list replacing or modifying some or all items in
place is not unpythonic. Sure, you could simply create a new list:

L = [1, 2, 3, 4]
newL = []
for item in L:
if item % 3 == 0:
newL.append(item)
else:
newL.append(item**2)

but that's wasteful if the list is big, or if the items are expensive to
copy.

Isn't this more elegant, and Pythonic?

L = [1, 2, 3, 4]
for index, item in enumerate(L):
if item % 3 != 0:
L[index] = item**2



-- 
Steven.

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


Re: why use special config formats?

2006-03-10 Thread Fuzzyman

[EMAIL PROTECTED] wrote:
> if you are really so scared of letting others exploit your config
> scripts, then use the second, pickled fashion. that way you can store
> the file at $HOME/blah-config.pkl, and everybody's happy.
>
> still, my point is we dont need special config mechanisms, since the
> builtin ones, like object persistency (sp) or python scripts are good
> enough, less buggy, and dont require you to learn thousands of config
> formats.
>

Well... ConfigObj uses the same format as ConfigParser, which the basic
ini style.

The message is that config files are for users, and so should be in a
format convenient for them - not for the machine.

Call your users cry-babies if yu want, you won't have many...

> and you can even edit pickled files by hand (protocol 0 i believe).
> it's not that complicated.
>

If you're happy with a hardwired config file, you don't need a config
file at all.

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> 
> -tomer

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


Mutable complex numbers [was Re: output formatting for classes]

2006-03-10 Thread Steven D'Aprano
On Fri, 10 Mar 2006 02:19:10 +0100, Schüle Daniel wrote:

> yeah, i miss some things in complex implementation
> for example c=complex()
> c.abs = 2**0.5
> c.angle = pi/2
> 
> should result in 1+1j :)

Smiley noted, but consider:

c = complex()
=> what is the value of c here?

c.abs = 2**0.5
=> what is c's value now?

c.angle = pi/2
=> now c has the value 1+1j
 
Objects with indeterminate values are rarely a good idea.

A better way would be for complex numbers to take a constructor that can
take arguments in either Cartesian or polar form. So, hypothetically, the
following would all be equivalent:

1+1j
complex(1,1)
complex(real=1, img=1)
complex(len=2**0.5, theta=pi/2)

Another alternative would be a function to construct polar form complex
numbers. It could be a plain function or a static method:

cmath.polar(2**0.5, pi/2) => 1+1j
complex.polar(2**0.5, pi/2) => 1+1j



-- 
Steven.

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

Re: Why property works only for objects?

2006-03-10 Thread Bruno Desthuilliers
Michal Kwiatkowski a écrit :
> Alex Martelli napisał(a):
> 
>>Wrong!  Of _course_ it's an option -- why do you think it matters at all
>>whether you're the creator of this object?!
>  
(snip)
>>
>>def insert_property(obj, name, getter, setter):
>>class sub(obj.__class__): pass
>>setattr(sub, name, property(getter, setter))
>>obj.__class__ = sub
>>
>>See?  Of COURSE you can subclass -- not hard at all, really.
> 
> 
> Let me understand it clearly. If I change __class__ of an object,
> existing attributes (so methods as well) 
> of an object are still
> accessible the same way and don't change its values. Only resolution of
> attributes/methods not found in object is changed, as it uses new
> version of __class__ to lookup names. Is this right?

Attributes, yes. Not methods. Methods are looked up in the class. But in 
the example above (brillant, as usual), Alex dynamically creates a 
subclass of obj.__class__, so inheritence takes care of methods lookup.


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


Re: Why property works only for objects?

2006-03-10 Thread Bruno Desthuilliers
Michal Kwiatkowski a écrit :
> Steven Bethard napisał(a):
> 
>>>Is there any method of making descriptors on per-object basis?
>>
>>I'm still not convinced that you actually want to, but you can write
>>your own descriptor to dispatch to the instance object (instead of the
>>type):
> 
> 
> Ok, this works for attributes I know a name of at class definition. What
> about other situations? I could possibly want to have different sets of
> attributes for instances of a class.

Then you want a different class for each different set of attributes.

> Is it still possible to do? I don't
> also like current solution, as it wraps things around, creating another
> attribute ('_x') in the process. Aren't there any cleaner solutions?
> 
> The problem is I have an instance of a given class (say BaseClass) and I
> want it to implement some attribute accesses as method calls. I'm not a
> creator of this object, so changing definition of BaseClass or
> subclassing it is not an option. 

What you want is delegation. Which is pretty easy with Python, look at 
__getattr__ and __setattr__.

> Code below doesn't work, but shows my
> intention:
> 
> # obj is instance of BaseClass
> def get_x(self):
> # ...
> def set_x(self, value):
> # ...
> obj.x = property(get_x, set_x)

class ObjWrapper(object):
   def __init__(self, obj):
 self.obj = obj

  # special case x
  def _get_x(self):
return self.obj.x

  def _set_x(self, value):
self.obj.x = value

  x = property(fget=_get_x, fset=_set_x)

  # default lookup, directly delegate to obj
  def __getattr__(self, name):
return getattr(self.obj, name)

  def __setattr__(self, name, value):
# this one is a bit more tricky
# and I don't remember it right now,
# but it's in the fine manual anyway

obj = ObjWrapper(obj)
obj.x # calls ObjWrapper._get_x()


> Changing __setattr__/__getattr__ of an object also doesn't work for the
> same reason: dictionary lookup is made only in class attributes,
> ommiting object attributes. It's confusing, because writting obj.x and
> obj.__getattribute__('x') gives a different results. There also seems
> not to be any clear way to define methods for objects. Something like:
> 
> class C(object):
> pass
> 
> def method(self):
> return self.x
> 
> c = c.x
> c.method = method
> c.method() # => AttributeError

import types
c.method = types.MethodType(method, c, c.__class__)

> So another question arise. Is it possible to make function a method (so
> it will receive calling object as first argument)?

Yeps, just wrap it in a Method object (cf above)

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


Re: beautiful soup library question

2006-03-10 Thread Erik Max Francis
[EMAIL PROTECTED] wrote:

> I'm trying to extract some information from an html file using
> beautiful soup.  The strings I want get are after br tags, eg:
> 
> 
> this info
> more info
> and more info
> 
> 
> I can navigate to the first br tag using find_next_sibling, but how do
> I get the string after the br's?
> br.contents is empty.

I'm not familiar with Beautiful Soup specifically, but this isn't how 
the  tag works.  Unlike a tag like  or , which need not be 
closed in HTML,  does not contain anything, it's just a line break. 
  If it were XHTML, it would be , indicating that it's a 
standalone tag.

Instead you want to traverse the contents of the font tag, taking into 
account line breaks that you encounter.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   Fear is an emotion indispensible for survival.
   -- Hannah Arendt
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lighter weight options to Python's logging package?

2006-03-10 Thread skip

Trent> Do you have any profile information for where in the logging
Trent> package the time is being spent?

Looking back at a recent run from a few days ago Formatter.formatTime()
seems to be a current problem.

We create our own LogRecord subclass.  Because that was such a heavyweight
operation, instead of calling logging.LogRecord.__init__ from our class's
constructor, I wound up inlining it and deleting the state it set that we
never used.

Trent> I don't know how much of a perf issue it is for you. Perhaps
Trent> tweaking your usage of the logging package (perhaps using custom
Trent> Loggers, Filters, outputters, etc.)  could be made "good enough".

We've done a bit already.  I will see if there's more we can do.  Our use of
the package is actually very simple.  All we do are log basic messages.  Our
Formatter instance includes the time, level and message.  That's it.  We
have no need for displaying exception info, don't do threads, don't mess
with the file or module names, etc.  The only thing we do that isn't
supported directly by the package is to use a compressing version of the
RotatingFileHandler class.

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


Re: Python and C

2006-03-10 Thread Terry Reedy

"P Boy" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I have recently found another approach by using ctypes
(http://starship.python.net/crew/theller/ctypes/).

Ctypes is now a 2.5 standard lib module and in being tested as such on 
multiple systems.

> I have a library from Microsoft, ewfapi.dll, ewfapi.lib (not required),
and ewfapi.h (from msdn.com)

Has anyone yet written a program to grab C struct declaration from the .h 
to produce code like

# Overlay configuration
class OverlayStoreConfig(ctypes.Structure):
_fields_ = [('FormatVersion',   ctypes.c_ulong),
('VolumeSize',  ctypes.c_longlong),
('NumSegments', ctypes.c_ulong),
('FreeSegments',ctypes.c_ulong),
('SegmentSize', ctypes.c_ulong),
('MaxVolumes',  ctypes.c_ulong),
('NumVolumes',  ctypes.c_ulong),
('MaxLevels',   ctypes.c_ushort),
('VolumeDescArray', pVolumeDesc),
]
?
Would save tedium and errors and make ctypes even more helpful.

Terry Jan Reedy



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


beautiful soup library question

2006-03-10 Thread meyerkp
Hi all,

I'm trying to extract some information from an html file using
beautiful soup.  The strings I want get are after br tags, eg:


this info
more info
and more info


I can navigate to the first br tag using find_next_sibling, but how do
I get the string after the br's?
br.contents is empty.

thanks for any ideas.

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


Re: why no block comments in Python?

2006-03-10 Thread Steven D'Aprano
On Thu, 09 Mar 2006 18:02:27 -0600, Terry Hancock wrote:

> On 9 Mar 2006 07:21:00 -0800
> "msoulier" <[EMAIL PROTECTED]> wrote:
>> > (and if you don't, you can quickly comment out regions
>> > by putting them inside a triple-quoted string.)
>> 
>> Although that will use up memory, as opposed to a comment.
> 
> Not really. Unless it is the first string in the block
> (class, function, module), it won't be assigned to anything,
> and will be immediately garbage-collected.
> 
> It may consume space in the pyc file, I'm not sure.

I don't believe this is true. Unassigned strings other than the doc string
are not compiled into the code:

>>> def f(x):
... "this is a doc string"
... "but this isn't"
... return "hello world"
...
>>> dis.dis(f)
  4   0 LOAD_CONST   1 ('hello world')
  3 RETURN_VALUE
  4 LOAD_CONST   2 (None)
  7 RETURN_VALUE


Strangely enough, this is a local optimization that appears to have been
done only for strings: 

>>> def g():
... 45
... return 55
...
>>> dis.dis(g)
  2   0 LOAD_CONST   1 (45)
  3 POP_TOP
 
  3   4 LOAD_CONST   2 (55)
  7 RETURN_VALUE
  8 LOAD_CONST   0 (None)
 11 RETURN_VALUE

So you should feel free to use strings (triple-quoted or otherwise) as
documentation in your functions.

-- 
Steven.

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


Re: Python Evangelism

2006-03-10 Thread Terry Reedy

"Tim Parkin" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>> Well, why don't we promote it as PyPI (Python Package Index)? The url
>> _is_ python.org/pypi, and I'm pretty sure I read somewhere that PyPI
>> was the intended name... If the community then decides on some
>> standardized automated package management, I'm sure PyPI (cheese shop)
>> would probably be the definitive repository.
>>
>> $ pypi install hello
>>
>> is much better than
>>
>> $ bluecheese install hello

Definitely

> I have to say I prefer pypi myself.

Strongly prefer.  Cheeseshop made no sense to me until explained.

> I think it's a great idea
> subtitling it 'cheeseshop' but referring to it directly as "cheeseshop"
> is confusing at best.

I think PieShop would be much funnier as a double pun on Py/Pi and as a 
subtle Python riff on the Cheeseshop sketch for those familiar with the 
latter.  I also remember something about a Python/Parrot pie fight.

> I've already had a few requests to change the text
> of the link on the home page to 'packages' or 'package index'.

Please at least make it a synonym.

Terry Jan Reedy



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


Re: lighter weight options to Python's logging package?

2006-03-10 Thread Trent Mick
[EMAIL PROTECTED] wrote]
> We use the standard logging package and frequently bump into performance
> issues with it (we log a lot of information).  When that happens, we then go
> through our code and dump a bunch of logging calls we think we can live
> without.  This invariably causes problems because we get overzealous and
> delete something we needed and are then unable to do some bit of post-mortem
> debugging until we add back in the missing logging and cut another release.
> 
> Before I consider writing something from scratch, is there something lighter
> weight "floating around" out there already?

Do you have any profile information for where in the logging package the
time is being spent? I don't know how much of a perf issue it is for
you. Perhaps tweaking your usage of the logging package (perhaps using
custom Loggers, Filters, outputters, etc.) could be made "good enough".

Trent


-- 
Trent Mick
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Lib/test/test_mimetools.py

2006-03-10 Thread matt
Hi,

in the file Lib/test/test_mimetools.py on line 30 the call to 
mimetools.choose_boundary() fails if the machine that the tests are 
running on does not have a hostname that maps to an IP address.

I would have thought that the test should be 'skipped' rather than fail?

I don't know if this has been discussed before but any feedback would be 
appreciated. 

Would any body be interested in a patch to make the test skip if 
hostname does not have an designated IP?

Thanks

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


lighter weight options to Python's logging package?

2006-03-10 Thread skip

We use the standard logging package and frequently bump into performance
issues with it (we log a lot of information).  When that happens, we then go
through our code and dump a bunch of logging calls we think we can live
without.  This invariably causes problems because we get overzealous and
delete something we needed and are then unable to do some bit of post-mortem
debugging until we add back in the missing logging and cut another release.

Before I consider writing something from scratch, is there something lighter
weight "floating around" out there already?

Thanks,

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


Re: Which GUI toolkit is THE best?

2006-03-10 Thread Alan Franzoni
invitro81 on comp.lang.python said: 

> again to make a choice is difficult; is there also some guy liking pyqt 
> is it worse or should it be avoided because of the licencing policy for 
> qt (which I also like..)?
> 
>   * Which one is the most fun to program with?
>   * Which one is the most easy to learn?
>   * Which one looks best?
>   * Which one is the most productive to program with?

Those are all hard questions. You might as well have asked 'which is the
best web framework'. It's not easy to tell ^_^ It highly depends on which
tasks you're aiming at.

wxPython is a pretty good 'all-round' and cross-platform library, and
includes some non-graphical features. It's got a drawback: it's a wrapper
for the wxwidgets library, and hence it's not very pythonic; you can solve
part of its unpythonicness using wax, which is not very well documented at
the time. wxGlade can be used to design GUI apps with little effort.

pyGTK works well, too. Recent versions perform well and are good looking on
Windows systems as well as Linux and Macs (if you provide an X server).
It's very well documented (better than wxPython, in my opinion) and its
license is quite permissive. It's unpythonic just like wxPython. Glade and
Gazpacho can be used to design GUI apps in a visual way.

pyGUI is a pyGTK-based graphic library which is designed from scratch to be
pythonic. It seems very, very promising but I can't tell you if it's
production-stable since I've tested it just a couple of times. It may be
the funniest and more productive toolkit ever.

FLTK was interesting but seems to lack maintenance and support, pyQT is a
bit 'unfree' for most uses. Tkinter is quite old stuff.

-- 
Alan Franzoni <[EMAIL PROTECTED]>
-
Togli .xyz dalla mia email per contattarmi.
Rremove .xyz from my address in order to contact me.
-
GPG Key Fingerprint:
5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why python doesn't use syntax like function(,,x) for default parameters?

2006-03-10 Thread Michal Kwiatkowski
Dmitry Anikin napisał(a):
> Some example (from real life).
> def ChooseItems(StartDate, EndDate, Filter):
> #function returns a set of some items in chronological order
> #from required interval possibly using filter
> 
> ChooseItems() #get everything
> ChooseItems('01.01.2000', ,SomeFilter) #get everything after a date
> using filter
> ChooseItems(, '01.01.2000') #get everything before a date
> ChooseItems(, , SomeFilter) #get everything using filter
> 
> Now compare this to something which (I hope) is rather pythonian
> 
> Seq[:] #get everything
> Seq[2::3] #get everything after an index using filter (filter every
> third value)
> Seq[:3] #get everythin before an index
> Seq[::4] #get everything using a filter
> 
> Do you see any significant difference?

You're not comparing what you should. Range has only 3 parameters and is
a standard part of a language. Even if it's not obvious for someone
which parameters mean what in different combinations, it's not that hard
to look up in a manual. But user-defined functions are allowed to have
any number of arguments, with any possible meaning. That means it's
impossible to learn to recognize arguments exclusively by position
(which can be done for range), you have to look up function definition
*each time*.

And please remember that when writing a function, you define defaults as
values that user will mostly consider as appropriate. So if he doesn't
define them, that means he doesn't care. And Python syntax shows exactly
this intention. Your proposed syntax doesn't, as it suggest something
that user should know about is going on.

Now look at your example rewritten with standard Python keyword syntax.
If you know nothing about ChooseItems function, which version in your
opinion is more informative?

# get everything
ChooseItems()
# get everything after a date using filter
ChooseItems(after='01.01.2000', filter_with=SomeFilter)
# get everything before a date
ChooseItems(before='01.01.2000')
# get everything using filter
ChooseItems(filter_with=SomeFilter)

> I understand that many do not need such a syntax, I don't understand
> why someone would be AGAINST it. I don't propose to CHANGE anything
> in python (right now this syntax is error anyway). What I propose is just
> ADD another way of calling a function with keyword parameters but using
> POSITIONS instead of NAMES. And sometimes position is easier to
> remember than name. Anyway, who wants names let them use names.
> Who wants positions let them use positions. But to have a CHOICE is
> always good. As far as the choice itself doesn't damage anything,
> and I don't think that my does.

With this attitude Python will end up being Perl. Current semantics of
calling functions are already good enough to write clean and
understandable code.

> I think that if we compare
> ChooseItems('01.01.2000', ,SomeFilter)
> and
> ChooseItems(StartDate='01.01.2000', Filter=SomeFilter)
> the first one is more readable, 'cos you see
> what is meant right away. In second one you have to
> actually READ the keyword names to understand.
> It's not the common case, of course, but still, why
> not have a choice to use it?

I still think reading is better than guessing. :) Choosing good names
for arguments is another important factor (as shown in last example) in
readability.

> Some other examples which might benefit
> SetDate(year, month, day)
> SetDate(, month+1) # set next month, leaving year and day
> SetDate(, , 31) # set to end of month, not changing year
> #(wrong date adjusted automatically, of course)

In Poland we usually write dates in day-month-year notation. Having
function calls like this:

SetDate(year=y, month=m, day=d)
SetDate(month=m+1)
SetDate(day=31)

will be understandable by anyone.

> Please, don't try to scare me with 25-parameter functions.
> This is not for them. But to remember positions of two to
> five parameters is actually easier (if their order has some
> logic) then what are their names: startDate ? beginDate?
> firstDate? openDate? Date1?

I must disagree. If you choose argument names wisely you won't have any
trouble remembering which is which.

> The same approach can be used with tuples:
> (, , z) = func() # returning three element tuple()
> You think
> z = func()[2]
> is actually more clear? - By the way, I want THIRD value,
> not SECOND. And tuples don't have keyword names, do they?

It's not cleaner. It's error-prone, as you may lost one comma somewhere.
You also have to literally count what is the index of returned tuple
value that will be binded to "z".

> Finally, if syntax
> func (None, None, 10)
> seems natural to you, I propose to make it even more
> natural: I don't want some "None" passed as argument,
> I don't want anything at all passed, so I just use empty space
> func ( , , 10)
> And the called func don't have to bother with checking
> None for EACH argument but will happily use defaults instead.

If you would write it as func(third=10) it would be clearer that
func(, , 10) and call

Re: image letter recognition

2006-03-10 Thread Michael

>> Is there an existing package for python that will perform simple letter
>> recognition from image files?  I'm specifically looking for a way to
>> read from a png file, but that can be changed.
>> 
> "simple letter recognition from image file" now there's an oxymoron.
>
> I've successfully used ExperVision's RTK OCR toolkit for Windows
> from Python.  Actually by using ctypes you should be able to call
> any of the many OCR engines that are available.  Alas, all that I
> found that were really good were not free (but I haven't looked in
> well over a year).
>   
Might look at these:

http://directory.fsf.org/claraocr.html
http://directory.fsf.org/ocrad.html

-- 
Michael McGlothlin, tech monkey
Tub Monkey
http://www.tubmonkey.com/

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


Which GUI toolkit is THE best?

2006-03-10 Thread dimitri pater
Hi,in stead of going for the "traditional" GUIS like wxPython, PyGtk and the like, you could consider using a browser based GUI. Try CherryPy for instance.  See also here: 

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442481regards,Dimitri On 3/10/06, 
invitro81 <
[EMAIL PROTECTED]> wrote:HelloI've recently learnt python and I do love it! I congratulate all those
geeks who produce this nice language; well, because I could be called anearby newbee I've decided to improve my abilities by writing my ownnice editor with python; so I've to choose among all those GUI toolkit's
available there..But I've no idea which one I should use to start with.. I've read thattkinter seems to be the de facto standart in the pyhon community; butwhy? Is it the best available one or are theire other reasons? I read
also a litte about wxpython and pygtk.. both are appealing to me butagain to make a choice is difficult; is there also some guy liking pyqtis it worse or should it be avoided because of the licencing policy for
qt (which I also like..)?* Which one is the most fun to program with?* Which one is the most easy to learn?* Which one looks best?* Which one is the most productive to program with?
--http://mail.python.org/mailman/listinfo/python-list
-- "All truth passes through three stages. First, it is ridiculed. Second, it is violently opposed. Third, it is accepted as being self-evident."
~Arthur Schopenhauer Please visit dimitri's website: www.serpia.org

-- "All truth passes through three stages. First, it is ridiculed. Second, it is violently opposed. Third, it is accepted as being self-evident."~Arthur Schopenhauer 
Please visit dimitri's website: www.serpia.org
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: MS Access db (mdb): viewing table attributes

2006-03-10 Thread BartlebyScrivener
Gau,

This prints the names of the columns in my database.

# Modification of
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/389535
# Instructions for customizing are at:
# http://www.egenix.com/files/python/mxODBC.html

import mx.ODBC.Windows as odbc

driv='DRIVER={Microsoft Access Driver (*.mdb)};DBQ=d:/Access
Databases/Quotations2005'

conn = odbc.DriverConnect(driv)
c = conn.cursor()

# get the column names from Table1
c.execute ("SELECT * FROM Table1")

# get column names
cols= [ i[0] for i in c.description ]
print '\n\ncols=',cols

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


Re: Python and C

2006-03-10 Thread P Boy
I have written some C extension before but it was pretty tedious. I
have recently found another approach by using ctypes
(http://starship.python.net/crew/theller/ctypes/). Which you develop
your C module in dynamic library (DLL in Windows world), the from
Python, you can call the C functions in the DLL using ctypes.

I have a library from Microsoft, ewfapi.dll, ewfapi.lib (not required),
and ewfapi.h (from msdn.com) which I want to program the EWF capability
in Windows XP Embedded. I was thinking about writing a Python C
extension for it, but using ctypes is much easier. I only need to
redefine some data structures from the header file, and not worry about
common C tasks such as memory management, reference counting, etc.


I have some sample usage in Python shown below, which I can
interactively control the EWF feature using Python shell (in an XP
embedded machine).


# ewf.py


import ctypes
import string


# These are the functions from the EWF API
##EwfMgrGetDriveLetterFromVolumeName(volumeName)
##
##EwfMgrVolumeNameListIsEmpty(volumeEntry)
##
##EwfMgrVolumeNameEntryPop(volumeEntry)
##
##EwfMgrVolumeNameListDelete
##
##EwfMgrOpenProtected
##
##EwfMgrClose = _ewfapiPy.EwfMgrClose
##
##EwfMgrClearCommand = _ewfapiPy.EwfMgrClearCommand
##
##EwfMgrSetPersistentData = _ewfapiPy.EwfMgrSetPersistentData
##
##EwfMgrGetPersistentData = _ewfapiPy.EwfMgrGetPersistentData
##
##EwfMgrCheckpoint = _ewfapiPy.EwfMgrCheckpoint
##
##EwfMgrRestore = _ewfapiPy.EwfMgrRestore
##
##EwfMgrDisable = _ewfapiPy.EwfMgrDisable
##
##EwfMgrEnable = _ewfapiPy.EwfMgrEnable
##
##EwfMgrCommit = _ewfapiPy.EwfMgrCommit
##
##EwfMgrCommitAndDisableLive = _ewfapiPy.EwfMgrCommitAndDisableLive
##
##EwfMgrCommitFile = _ewfapiPy.EwfMgrCommitFile
##
##EwfMgrSetLevel = _ewfapiPy.EwfMgrSetLevel
##
##EwfMgrGetProtectedVolumeConfig =
_ewfapiPy.EwfMgrGetProtectedVolumeConfig
##
##EwfMgrGetProtectedVolumeList = _ewfapiPy.EwfMgrGetProtectedVolumeList

##
##EwfMgrOpenOverlayStore = _ewfapiPy.EwfMgrOpenOverlayStore
##
##EwfMgrGetOverlayStoreConfig = _ewfapiPy.EwfMgrGetOverlayStoreConfig
##
##EwfMgrRegisterLowSpaceNotification =
_ewfapiPy.EwfMgrRegisterLowSpaceNotification


# Short handle to the API
ewfapi = ctypes.windll.ewfapi


# Data structure from EWFAPI.h translated into Python


# Map these enumerations to string
EWF_CMD = { 0 : 'NO Command',
1 : 'Enable',
2 : 'Disable',
3 : 'Set Level',
4 : 'Commit',
}


EWF_STATE = { 0 : 'Enabled',
  1 : 'Disabled',
  }


EWF_TYPE = { 0 : 'Disk',
 1 : 'RAM',
 2 : 'RAM Reg',
 }


# Forward Declaration
pVolumeNameEntry = ctypes.POINTER('VolumeNameEntry')


# Structure of a linked-list
class VolumeNameEntry(ctypes.Structure):
_fields_ = [('Next', ctypes.POINTER(pVolumeNameEntry)),
('Name', ctypes.c_wchar * 256),
]


# Set the pointer to the structure
ctypes.SetPointerType(pVolumeNameEntry, VolumeNameEntry)


# Volume descriptor
class VolumeDesc(ctypes.Structure):
_fields_ = [('DeviceName',  ctypes.c_wchar * 256),
('VolumeID',ctypes.c_ubyte * 16),
]


pVolumeDesc = ctypes.POINTER(VolumeDesc)


# Overlay configuration
class OverlayStoreConfig(ctypes.Structure):
_fields_ = [('FormatVersion',   ctypes.c_ulong),
('VolumeSize',  ctypes.c_longlong),
('NumSegments', ctypes.c_ulong),
('FreeSegments',ctypes.c_ulong),
('SegmentSize', ctypes.c_ulong),
('MaxVolumes',  ctypes.c_ulong),
('NumVolumes',  ctypes.c_ulong),
('MaxLevels',   ctypes.c_ushort),
('VolumeDescArray', pVolumeDesc),
]


pOverlayStoreConfig = ctypes.POINTER(OverlayStoreConfig)


class Command(ctypes.Structure):
_fields_ = [('Command', ctypes.c_int),
('Param1',  ctypes.c_ulong),
('Param2',  ctypes.c_ulong),
]


pCommand = ctypes.POINTER(Command)


class FileTime(ctypes.Structure):
_fields_ = [('LowDateTime', ctypes.c_ulong),
('HighDateTime', ctypes.c_ulong),
]


pFileTime = ctypes.POINTER(FileTime)


class LevelDesc(ctypes.Structure):
_fields_ = [('LevelName', ctypes.c_wchar * 64),
('LevelEndTime', FileTime),
('LevelDataSize', ctypes.c_longlong),
]


pLevelDesc = ctypes.POINTER(LevelDesc)


class VolumeConfig(ctypes.Structure):
_fields_ = [('Type',ctypes.c_int),
('State',   ctypes.c_int),
('BootCommand', Command),
('PersistentData',  ctypes.c_ubyte * 32),
('MaxLevels',   ctypes.c_ushort),
('ClumpSize',   ctypes.c_ulong),
('CurrentLevel',ctypes.c_ushort),
('DiskMap_RamDataSize', ctypes

Re: XML international characters

2006-03-10 Thread Martin v. Löwis
Andreas R. wrote:
> When parsing XML documents containing international characters, such as
> the Norwegian characters Æ, Ø, Å, I get an exception in Python's SAX
> module. What is the correct way to parse such characters in Python? I've
> searched for methods to somehow escape the characters, without any luck
> so far.

The correct way is to provide correct XML. If you get a parse error,
it really means that there is an error in your XML file. Most likely,
the encoding of the characters is inconsistent with the declared
encoding. Notice that the default encoding of XML (in absence of a
declaration) is UTF-8.

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


XML international characters

2006-03-10 Thread Andreas R.
Hello,

When parsing XML documents containing international characters, such as 
the Norwegian characters Æ, Ø, Å, I get an exception in Python's SAX 
module. What is the correct way to parse such characters in Python? I've 
searched for methods to somehow escape the characters, without any luck 
so far.


Thanks in advance,
Andreas

www.openrts.org - Python RTS game
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python and C

2006-03-10 Thread P Boy
I have written some C extension before but it was pretty tedious. I
have recently found another approach by using ctypes
(http://starship.python.net/crew/theller/ctypes/). Which you develop
your C module in dynamic library (DLL in Windows world), the from
Python, you can call the C functions in the DLL using ctypes.

I have a library from Microsoft, ewfapi.dll, ewfapi.lib (not required),
and ewfapi.h (see download) which I want to program the EWF capability
in Windows XP Embedded. I was thinking about writing a Python C
extension for it, but using ctypes is much easier. I only need to
redefine some data structures from the header file, and not worry about
common C tasks such as memory management, reference counting, etc.

Ewfapi files can be downloaded from
http://www.microsoft.com/downloads/details.aspx?FamilyID=eb3b3d35-ae95-4864-ba3c-d488d3980972&displaylang=en

I have some sample usage in Python shown below, which I can
interactively control the EWF feature using Python shell (in an XP
embedded machine).


# ewf.py

import ctypes
import string

# These are the functions from the EWF API
##EwfMgrGetDriveLetterFromVolumeName(volumeName)
##
##EwfMgrVolumeNameListIsEmpty(volumeEntry)
##
##EwfMgrVolumeNameEntryPop(volumeEntry)
##
##EwfMgrVolumeNameListDelete
##
##EwfMgrOpenProtected
##
##EwfMgrClose = _ewfapiPy.EwfMgrClose
##
##EwfMgrClearCommand = _ewfapiPy.EwfMgrClearCommand
##
##EwfMgrSetPersistentData = _ewfapiPy.EwfMgrSetPersistentData
##
##EwfMgrGetPersistentData = _ewfapiPy.EwfMgrGetPersistentData
##
##EwfMgrCheckpoint = _ewfapiPy.EwfMgrCheckpoint
##
##EwfMgrRestore = _ewfapiPy.EwfMgrRestore
##
##EwfMgrDisable = _ewfapiPy.EwfMgrDisable
##
##EwfMgrEnable = _ewfapiPy.EwfMgrEnable
##
##EwfMgrCommit = _ewfapiPy.EwfMgrCommit
##
##EwfMgrCommitAndDisableLive = _ewfapiPy.EwfMgrCommitAndDisableLive
##
##EwfMgrCommitFile = _ewfapiPy.EwfMgrCommitFile
##
##EwfMgrSetLevel = _ewfapiPy.EwfMgrSetLevel
##
##EwfMgrGetProtectedVolumeConfig =
_ewfapiPy.EwfMgrGetProtectedVolumeConfig
##
##EwfMgrGetProtectedVolumeList = _ewfapiPy.EwfMgrGetProtectedVolumeList
##
##EwfMgrOpenOverlayStore = _ewfapiPy.EwfMgrOpenOverlayStore
##
##EwfMgrGetOverlayStoreConfig = _ewfapiPy.EwfMgrGetOverlayStoreConfig
##
##EwfMgrRegisterLowSpaceNotification =
_ewfapiPy.EwfMgrRegisterLowSpaceNotification

# Short handle to the API
ewfapi = ctypes.windll.ewfapi

# Data structure from EWFAPI.h translated into Python

# Map these enumerations to string
EWF_CMD = { 0 : 'NO Command',
1 : 'Enable',
2 : 'Disable',
3 : 'Set Level',
4 : 'Commit',
}

EWF_STATE = { 0 : 'Enabled',
  1 : 'Disabled',
  }

EWF_TYPE = { 0 : 'Disk',
 1 : 'RAM',
 2 : 'RAM Reg',
 }

# Forward Declaration
pVolumeNameEntry = ctypes.POINTER('VolumeNameEntry')

# Structure of a linked-list
class VolumeNameEntry(ctypes.Structure):
_fields_ = [('Next', ctypes.POINTER(pVolumeNameEntry)),
('Name', ctypes.c_wchar * 256),
]

# Set the pointer to the structure
ctypes.SetPointerType(pVolumeNameEntry, VolumeNameEntry)


# Volume descriptor
class VolumeDesc(ctypes.Structure):
_fields_ = [('DeviceName',  ctypes.c_wchar * 256),
('VolumeID',ctypes.c_ubyte * 16),
]

pVolumeDesc = ctypes.POINTER(VolumeDesc)


# Overlay configuration
class OverlayStoreConfig(ctypes.Structure):
_fields_ = [('FormatVersion',   ctypes.c_ulong),
('VolumeSize',  ctypes.c_longlong),
('NumSegments', ctypes.c_ulong),
('FreeSegments',ctypes.c_ulong),
('SegmentSize', ctypes.c_ulong),
('MaxVolumes',  ctypes.c_ulong),
('NumVolumes',  ctypes.c_ulong),
('MaxLevels',   ctypes.c_ushort),
('VolumeDescArray', pVolumeDesc),
]

pOverlayStoreConfig = ctypes.POINTER(OverlayStoreConfig)

class Command(ctypes.Structure):
_fields_ = [('Command', ctypes.c_int),
('Param1',  ctypes.c_ulong),
('Param2',  ctypes.c_ulong),
]

pCommand = ctypes.POINTER(Command)

class FileTime(ctypes.Structure):
_fields_ = [('LowDateTime', ctypes.c_ulong),
('HighDateTime', ctypes.c_ulong),
]

pFileTime = ctypes.POINTER(FileTime)

class LevelDesc(ctypes.Structure):
_fields_ = [('LevelName', ctypes.c_wchar * 64),
('LevelEndTime', FileTime),
('LevelDataSize', ctypes.c_longlong),
]

pLevelDesc = ctypes.POINTER(LevelDesc)


class VolumeConfig(ctypes.Structure):
_fields_ = [('Type',ctypes.c_int),
('State',   ctypes.c_int),
('BootCommand', Command),
('PersistentData',  ctypes.c_ubyte * 32),
('MaxLevels',   ctypes.c_ushort),
('ClumpSize',   

Re: image letter recognition

2006-03-10 Thread Larry Bates
[EMAIL PROTECTED] wrote:
> Is there an existing package for python that will perform simple letter
> recognition from image files?  I'm specifically looking for a way to
> read from a png file, but that can be changed.
> 
"simple letter recognition from image file" now there's an oxymoron.

I've successfully used ExperVision's RTK OCR toolkit for Windows
from Python.  Actually by using ctypes you should be able to call
any of the many OCR engines that are available.  Alas, all that I
found that were really good were not free (but I haven't looked in
well over a year).

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


Re: MS Access db (mdb): viewing table attributes

2006-03-10 Thread Larry Bates
[EMAIL PROTECTED] wrote:
> I have an Access 2003 database, protected by a workgroup, that I am
> trying to view through python.  Currently, I'm attempting dao with the
> win32 package, and I'm able to view all of the table names, but I don't
> know how to view the attributes of the tables.
> 
> My code:
> 
> import win32com.client
> from pprint import pprint
> 
> #sample code to list all tables in the selected database
> daoEngine = win32com.client.Dispatch('DAO.DBEngine.36')
> dtbs = daoEngine.OpenDatabase('database_file.mdb')
> for table in dtbs.TableDefs:
> if table.Name[:4] <> "MSys" and table.Name[:4] <> "~TMP":
> pprint(table.Name.encode('utf-8'))
> #the above works, but below does not:
> for col in table.Fields:
>  pprint(col.Name, Col.Type, Col.Size)
> 
> I am getting that len(Fields) = 0, and I know the database tables are
> all full of columns (and data).  Is there also some resource that
> defines all the properties of TableDefs?  I wasn't able to find a
> python reference for this.
> 
> Thank You,
> Gau
> 
Not quite sure about DAO but when I use ODBC I get the fieldnames
by doing (stripped from working program):

crsr.execute(SQL_query)
fieldinfo=crsr.description
fieldnames=["%s" % i[0].lower() for i in fieldinfo]

Hope this helps.

-Larry Bates

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


Re: creating variable in root namespace from module

2006-03-10 Thread Duncan Booth
MakaMaka wrote:

> Ok, I figured it out.  Thanks for your help guys.  If anybody else is
> searching this group looking for the answer, you want the
> sys._getframe() function.
> 
> sys._getframe(1).f_locals['a'] = 1
> 
> if you put the above in a function in a module, it creates a variable
> 'a' in the namespace of whatever calls the function in the module.  I
> know this may make people cringe, but since I'm trying to basically
> create a language, of which python is a subset, it's actually exactly
> what I need to do.
> 

Err, no. Actually it doesn't:

>>> import sys
>>> def f():
sys._getframe(1).f_locals['a'] = 1


>>> def g():
a = 0
print a
f()
print a


>>> g()
0
0
>>> a = 42
>>> f()
>>> a
1
>>> 

Code like that may sometime update the caller's namespace, but for local 
variables it will usually have no effect. Also, any effect it does have may 
vary wildly across different Python implementations or versions.

In short, don't do that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: epydoc help (putting XML in docstrings)

2006-03-10 Thread [EMAIL PROTECTED]
Doh.  That was too easy.

Thanks!
jw

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


Setting permissions/ownership/destination in distutils?

2006-03-10 Thread [EMAIL PROTECTED]
Is there a recommended way to specify the permissions and ownership of
scripts installed from distutils?   Also, I'm currently just using this
config in setup.cfg to control where the scripts go:

[install]
install-scripts = /opt/mcad/bin

But it would be very helpful if I could install some of the scripts in
another location.  Any good way to do that?

Thanks!

-Ben

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


Re: epydoc help (putting XML in docstrings)

2006-03-10 Thread Jean-Paul Calderone
On 10 Mar 2006 12:49:29 -0800, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>Hi everyone!  I'm documenting some functions that return XML strings.
>I'd like to have `sample' xml show up in my epydoc generated
>documentation.  However, epydoc does not like the indentation of the
>XML and gives me this error ->
>
>L28: Error: Improper paragraph indentation.
>
>Here is a simple function that epydoc does not like:
>
>def test():
>"""
>Return an XML string that looks like this::
>
>
>  123
>  D
>  ...
>
>
>@return: XML string.
>"""
>pass
>
>[EMAIL PROTECTED]:daplib]$ epydoc test.py
>Importing 1 modules.
>  [.]
>Building API documentation for 1 modules.
>  [.]
>===
>C:\cygwin\home\jwyant\code\dap-support\python\daplib\test.py
>In test.test docstring (line 2):
>---
>   L5: Error: Improper paragraph indentation.
>
>Any ideas?
>

def test():
"""
Return an XML string that looks like this::


  123
  D
  ...


@return: XML string.
"""

[EMAIL PROTECTED]:~$ epydoc test.py 
Importing 1 modules.
  [.]
Building API documentation for 1 modules.
  [.]
Writing HTML docs (10 files) to 'html'.
  [..]

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


Re: MS Access db (mdb): viewing table attributes

2006-03-10 Thread BartlebyScrivener
>> How can I get the names of the columns for each table??

SELECT * FROM mytable

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


Re: epydoc help (putting XML in docstrings)

2006-03-10 Thread James Stroud
[EMAIL PROTECTED] wrote:
> Hi everyone!  I'm documenting some functions that return XML strings.
> I'd like to have `sample' xml show up in my epydoc generated
> documentation.  However, epydoc does not like the indentation of the
> XML and gives me this error ->
> 
> L28: Error: Improper paragraph indentation.
> 
> Here is a simple function that epydoc does not like:
> 
> def test():
> """
> Return an XML string that looks like this::
> 
> 
>   123
>   D
>   ...
> 
> 
> @return: XML string.
> """
> pass
> 
> [EMAIL PROTECTED]:daplib]$ epydoc test.py
> Importing 1 modules.
>   [.]
> Building API documentation for 1 modules.
>   [.]
> ===
> C:\cygwin\home\jwyant\code\dap-support\python\daplib\test.py
> In test.test docstring (line 2):
> ---
>L5: Error: Improper paragraph indentation.
> 
> Any ideas?
> 
> Thanks!
> 

Just indent the xml:

def test():
 """
 Return an XML string that looks like this::

 
   123
   D
   ...
 

 @return: XML string.
 """
 pass

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why use special config formats?

2006-03-10 Thread Sybren Stuvel
[EMAIL PROTECTED] enlightened us with:
> i dont know about your experience with config files, but there
> thousands of formats.

All the config files I needed were either very easy to learn, or well
documented in comments.

> on the python side -- just in this conversation, we mentioned
> ConfigObj, ConfigParser and the Config module i linked to.  when
> everybody writes his own config, you get loads of unique formats.

Hence the Python modules.

> anyway, for all the cry-babies here that can't edit pickle files.
> okay -- just load() them, change what you want, and dump() them.
> don't cry.

You really need to get real here. Configuration files are for *users*,
not programmers. You can't expect a user to learn about Python in
general and about pickle in specific.

> and if you insist, i'm sure there's a python serializer to
> XML/SOAP/whatever other readble format.

Which then gives you another configuration format to learn...

> and for security issues -- usually config files are edited by
> admins, so that's not a problem.

You go explain that to someone who just wants to edit his mail
client's config file.

> and per-user config files (at $HOME), can easily be achieved with
> execfile().

Which is then totally insecure. An exploit can easily be made then -
just inject a rootkit downloading & starting script into someone's
email client configuration file and boom, computer is hacked.

> the point is NOT TO WRITE A PARSER for every config file.

Hence standard config file formats and parser modules.

> * usually admins change the configuration, and they have too much
> power anyway

Admins have too much power? Go get an education.

> * if you worry about security/too much power, pickle your config

Sure, and where would you keep your comments explaining the
configuration fields?

> but inventing proprietary formats with unique syntaxes, and having
> to write and debug parsers for them -- that's stupid.

Which is why there are standard modules for them.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MS Access db (mdb): viewing table attributes

2006-03-10 Thread gau . tai
For more reference, I got my information to start this from:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52267

When I try to run that code, it gives me this:
  File "C:\Python24\Lib\site-packages\win32com\client\util.py", line
83, in next
return _get_good_object_(self._iter_.next())
pywintypes.com_error: (-2146825178, 'OLE error 0x800a0c26', None, None)

The error is pointing to:
"for idx in currTabl.Indexes:"

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


Re: Simple questions on use of objects (probably faq)

2006-03-10 Thread Brian Elmegaard
bruno at modulix <[EMAIL PROTECTED]> writes:

> I should just take some time and learn to read !-)

Then I am better of than you. I just had to learn the syntax of a
language :-)
-- 
Brian (remove the sport for mail)
http://www.et.web.mek.dtu.dk/Staff/be/be.html
http://www.rugbyklubben-speed.dk
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Evangelism

2006-03-10 Thread Tim Churches
Benny wrote:
> Paul Boddie wrote:
> 
>> Bizarre names may be cute (to some people) but they don't lend
>> themselves to guessing or searching. Consequently, people who want
>> answers yesterday aren't likely to be amused to eventually discover
>> that the name of the resource they've been looking for is some opaque,
>> three-levels-of-indirection-via-irony, in-crowd joke. And even acronyms
>> like CPAN are better than wacky names, anyway.
> 
> To emphasize the point as a newbie: I know what CPAN is. I would go to 
> the Vaults of Parnassus for Python stuff. But Cheese Shop?

I like the irony of the name Cheese Shop, but I do think that there is a
problem with "Shop", as it typically means a place where you buy things
for money. However, the vast majority of the cheesy comestibles at the
Cheese Shop are available for free. In fact, of 1287 packages currently
listed there, only 7 have non-free or proprietary licenses. Actually, it
was the "National Cheese Emporium" in the original sketch, although Mr
Wensleydale does describe it as a cheese shop - but both "shop" and
"emporium" are used to describe places of commerce. On re-acquaintance,
the sketch itself is still very funny after all these years, except
perhaps for the ending, in which Mousebender shoots dead Mr Wensleydale
for deliberately wasting his time. In the early 1970s in Britain, when
shooters were possessed by a very small minority of blaggards, that
might have been funny, but in the early 21st century, I find it grates a
little (no pun intended) - I can imagine the same fate befalling a
latter-day Wensleydale in a different country who happens to be fresh
out of meira. But I am sure ESR would defend Mousebender's right to blow
poor Wensleydale away - see http://www.catb.org/~esr/guns/gun-ethics.html .

So is there an alternative Monty Python sketch which has a theme of
purveyance as opposed to commerce? None spring to mind.

Tim C




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


Re: read/ edit line from stdin

2006-03-10 Thread Clemens Hepper
It's a bit more complicated.
The field has a default and a preassigned Value.

The default is p.e. 'localhost' and the value is 'www.gentoo.org'.
Then localhost is chosen if the value is erased to ''. But i want to
make it easy to keep the preassigned value!
So if nothing is typed 'www.gentoo.org' should be used.

I just thought that extending the commandline input interface would
be quite useful.
I want a text field that can be edited like common GUI-TextFields on
command line...

mfg
- eth

James Stroud wrote:
> Clemens Hepper wrote:
>> Hello,
>> for my project confux (http://confux.sourceforge.net) I want to read
>> a line from stdin.
>> But I don't want the user to type a new line. I want so display a
>> value which the user can edit.
>>
>> For example I want to ask the user for a hostname and I print
>> "localhost", the user modified it to "localserver" and I read it
>> after .
>>
>> What is the fastest way to realize that? I do NOT want to use curses
>> (yet) ;-).
>>
>> mfg
>> - eth
> 
> Why don't you just make "localhost" the default and have the user enter
> the complete name if they want it different. Seems like this is the way
> every CL program I've ever seen works.
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MS Access db (mdb): viewing table attributes

2006-03-10 Thread gau . tai
BartlebyScrivener:

Maybe you're right, and I'll try posting to another group.  However, I
have found resources for doing this using the same data structure:
"TableDefs" which is in VB and python.  I see how they are doing it in
VB, but I don't know how this works in python.  I was hoping someone
could at least point me to the details of this object, so I could then
examine it's properties myself.  In VB, it looks like it's more of a
property of the object and not an SQL query.

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


epydoc help (putting XML in docstrings)

2006-03-10 Thread [EMAIL PROTECTED]
Hi everyone!  I'm documenting some functions that return XML strings.
I'd like to have `sample' xml show up in my epydoc generated
documentation.  However, epydoc does not like the indentation of the
XML and gives me this error ->

L28: Error: Improper paragraph indentation.

Here is a simple function that epydoc does not like:

def test():
"""
Return an XML string that looks like this::


  123
  D
  ...


@return: XML string.
"""
pass

[EMAIL PROTECTED]:daplib]$ epydoc test.py
Importing 1 modules.
  [.]
Building API documentation for 1 modules.
  [.]
===
C:\cygwin\home\jwyant\code\dap-support\python\daplib\test.py
In test.test docstring (line 2):
---
   L5: Error: Improper paragraph indentation.

Any ideas?

Thanks!

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


Re: MS Access db (mdb): viewing table attributes

2006-03-10 Thread gau . tai
That would be fine for me to switch to mxodbc, I've used it before and
it worked fine.  But if I switch, do you know how I can get the column
names from the table?  Maybe I'm not being clear with my question here.
 I'm going to try again

here's a table (it's in access):

=== tablename = mytable ===

id   |   user   |  pass   |   access privileges <-- these are the
column names I want

0bob  12345 admin/full
1sam 53432 power user
4mike43234 guest

I know how to connect to the database.
I know how to get the table names.
How can I get the names of the columns for each table??

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


Re: MS Access db (mdb): viewing table attributes

2006-03-10 Thread BartlebyScrivener
>> I was hoping that your code would
>> return the column names for me, but it was expecting me to list the
>> columns to use.  I want to know how to retrieve that list of columns
>> through python.

I think once  you establish connection to the database using Python and
mxODBC, then your question becomes an SQL question not a Python
question. 

rpd

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


Re: read/ edit line from stdin

2006-03-10 Thread James Stroud
Clemens Hepper wrote:
> Hello,
> for my project confux (http://confux.sourceforge.net) I want to read
> a line from stdin.
> But I don't want the user to type a new line. I want so display a
> value which the user can edit.
> 
> For example I want to ask the user for a hostname and I print
> "localhost", the user modified it to "localserver" and I read it
> after .
> 
> What is the fastest way to realize that? I do NOT want to use curses
> (yet) ;-).
> 
> mfg
> - eth

Why don't you just make "localhost" the default and have the user enter 
the complete name if they want it different. Seems like this is the way 
every CL program I've ever seen works.

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MS Access db (mdb): viewing table attributes

2006-03-10 Thread BartlebyScrivener
Gau,

I'm a beginner and had fits connecting to my Access 2003 DB of
quotations. The best advice that finally worked for me was to use
mxODBC. In fact, you might just search this forum for Access and
mxODBC.

I can't customize to fit your situation, but here is the connection
part of a script I use to extract a random quote. I'm on Windows XP
using newest Python from ActiveState.

# Based on
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/389535
# Instructions for customizing are at:
# http://www.egenix.com/files/python/mxODBC.html

import mx.ODBC.Windows as odbc
import random
import textwrap

driv='DRIVER={Microsoft Access Driver (*.mdb)};DBQ=d:/Access
Databases/Quotations2005'

conn = odbc.DriverConnect(driv)
c = conn.cursor()

# Just counts the quotes, doesn't select them
c.execute ("SELECT COUNT(Quote) FROM Table1")

# Yields the number of rows with something in the quote field
total_quotes = c.fetchone()

# Get a random number somewhere between
# 1 and the number of total quotes

quote_number = random.randint(1, total_quotes[0])

# Select a quote where the ID matches that number
c.execute ("SELECT Author, Quote FROM QUOTES7 WHERE ID = %d" %
quote_number)

quote = c.fetchone()

The rest of the script just deals with formatting and presentation of
the quote.

Hope this helps.

rpd

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


Re: time series calculation in list comprehension?

2006-03-10 Thread Lonnie Princehouse
Well, you could iterate over an index into the list:

  from __future__ import division

  def moving_average(sequence, n):
  return [sum(sequence[i:i+n])/n for i in
xrange(len(sequence)-n+1)]

Of course, that's hardly efficient.  You really want to use the value
calculated for the i_th term in the (i+1)th term's evaluation.  While
it's not easy (or pretty) to store state between iterations in a list
comprehension, this is the perfect use for a generator:

  def generator_to_list(f):
return lambda *args,**keywords: list(f(*args,**keywords))

  @generator_to_list
  def moving_average(sequence, n):
assert len(sequence) >= n and n > 0
average = sum(sequence[:n]) / n
yield average
for i in xrange(1, len(sequence)-n+1):
  average += (sequence[i+n-1] - sequence[i-1]) / n
  yield average

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


Re: Python cleanup on exit

2006-03-10 Thread Steve Juranich
Jacob Kroon wrote:

> Is there another way to make python delete objects which were
> created in the global scope upon exit ?

Check out the `atexit' module.
-- 
Steve Juranich
Tucson, AZ
USA

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


Re: Why python doesn't use syntax like function(, , x) for default parameters?

2006-03-10 Thread Dmitry Anikin
Some example (from real life).
def ChooseItems(StartDate, EndDate, Filter):
#function returns a set of some items in chronological order
#from required interval possibly using filter

ChooseItems() #get everything
ChooseItems('01.01.2000', ,SomeFilter) #get everything after a date using filter
ChooseItems(, '01.01.2000') #get everything before a date
ChooseItems(, , SomeFilter) #get everything using filter

Now compare this to something which (I hope) is rather pythonian

Seq[:] #get everything
Seq[2::3] #get everything after an index using filter (filter every third value)
Seq[:3] #get everythin before an index
Seq[::4] #get everything using a filter

Do you see any significant difference?

I understand that many do not need such a syntax, I don't understand
why someone would be AGAINST it. I don't propose to CHANGE anything
in python (right now this syntax is error anyway). What I propose is just
ADD another way of calling a function with keyword parameters but using
POSITIONS instead of NAMES. And sometimes position is easier to
remember than name. Anyway, who wants names let them use names.
Who wants positions let them use positions. But to have a CHOICE is
always good. As far as the choice itself doesn't damage anything,
and I don't think that my does.

I think that if we compare
ChooseItems('01.01.2000', ,SomeFilter)
and
ChooseItems(StartDate='01.01.2000', Filter=SomeFilter)
the first one is more readable, 'cos you see
what is meant right away. In second one you have to
actually READ the keyword names to understand.
It's not the common case, of course, but still, why
not have a choice to use it?

Some other examples which might benefit
SetDate(year, month, day)
SetDate(, month+1) # set next month, leaving year and day
SetDate(, , 31) # set to end of month, not changing year
#(wrong date adjusted automatically, of course)

FormatFloat(Float, Length, Precision, FormatFlags)
You might want precision, leaving length default, or just use FormatFlags

In fact, I became so used to convenience of such syntax that
it was a disappointment not to find it in python.

Please, don't try to scare me with 25-parameter functions.
This is not for them. But to remember positions of two to
five parameters is actually easier (if their order has some
logic) then what are their names: startDate ? beginDate?
firstDate? openDate? Date1?

The same approach can be used with tuples:
(, , z) = func() # returning three element tuple()
You think
z = func()[2]
is actually more clear? - By the way, I want THIRD value,
not SECOND. And tuples don't have keyword names, do they?
And what about
(a, , b)  = func()
...well, maybe I got carried away a little...

Finally, if syntax
func (None, None, 10)
seems natural to you, I propose to make it even more
natural: I don't want some "None" passed as argument,
I don't want anything at all passed, so I just use empty space
func ( , , 10)
And the called func don't have to bother with checking
None for EACH argument but will happily use defaults instead.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why python doesn't use syntax like function(, , x) for default parameters?

2006-03-10 Thread Dmitry Anikin
Some example (from real life).
def ChooseItems(StartDate, EndDate, Filter):
#function returns a set of some items in chronological order
#from required interval possibly using filter

ChooseItems() #get everything
ChooseItems('01.01.2000', ,SomeFilter) #get everything after a date using filter
ChooseItems(, '01.01.2000') #get everything before a date
ChooseItems(, , SomeFilter) #get everything using filter

Now compare this to something which (I hope) is rather pythonian

Seq[:] #get everything
Seq[2::3] #get everything after an index using filter (filter every third value)
Seq[:3] #get everythin before an index
Seq[::4] #get everything using a filter

Do you see any significant difference?

I understand that many do not need such a syntax, I don't understand
why someone would be AGAINST it. I don't propose to CHANGE anything
in python (right now this syntax is error anyway). What I propose is just
ADD another way of calling a function with keyword parameters but using
POSITIONS instead of NAMES. And sometimes position is easier to
remember than name. Anyway, who wants names let them use names.
Who wants positions let them use positions. But to have a CHOICE is
always good. As far as the choice itself doesn't damage anything,
and I don't think that my does.

I think that if we compare
ChooseItems('01.01.2000', ,SomeFilter)
and
ChooseItems(StartDate='01.01.2000', Filter=SomeFilter)
the first one is more readable, 'cos you see
what is meant right away. In second one you have to
actually READ the keyword names to understand.
It's not the common case, of course, but still, why
not have a choice to use it?

Some other examples which might benefit
SetDate(year, month, day)
SetDate(, month+1) # set next month, leaving year and day
SetDate(, , 31) # set to end of month, not changing year
#(wrong date adjusted automatically, of course)

FormatFloat(Float, Length, Precision, FormatFlags)
You might want precision, leaving length default, or just use FormatFlags

In fact, I became so used to convenience of such syntax that
it was a disappointment not to find it in python.

Please, don't try to scare me with 25-parameter functions.
This is not for them. But to remember positions of two to
five parameters is actually easier (if their order has some
logic) then what are their names: startDate ? beginDate?
firstDate? openDate? Date1?

The same approach can be used with tuples:
(, , z) = func() # returning three element tuple()
You think
z = func()[2]
is actually more clear? - By the way, I want THIRD value,
not SECOND. And tuples don't have keyword names, do they?
And what about
(a, , b)  = func()
...well, maybe I got carried away a little...

Finally, if syntax
func (None, None, 10)
seems natural to you, I propose to make it even more
natural: I don't want some "None" passed as argument,
I don't want anything at all passed, so I just use empty space
func ( , , 10)
And the called func don't have to bother with checking
None for EACH argument but will happily use defaults instead.
-- 
http://mail.python.org/mailman/listinfo/python-list


read/ edit line from stdin

2006-03-10 Thread Clemens Hepper
Hello,
for my project confux (http://confux.sourceforge.net) I want to read
a line from stdin.
But I don't want the user to type a new line. I want so display a
value which the user can edit.

For example I want to ask the user for a hostname and I print
"localhost", the user modified it to "localserver" and I read it
after .

What is the fastest way to realize that? I do NOT want to use curses
(yet) ;-).

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


Re: Python Evangelism

2006-03-10 Thread Tim Parkin
Andrew Gwozdziewycz wrote:
>  > To emphasize the point as a newbie: I know what CPAN is. I would go to
> 
>>the Vaults of Parnassus for Python stuff. But Cheese Shop?
>>
> 
> 
> Well, why don't we promote it as PyPI (Python Package Index)? The url
> _is_ python.org/pypi, and I'm pretty sure I read somewhere that PyPI
> was the intended name... If the community then decides on some
> standardized automated package management, I'm sure PyPI (cheese shop)
> would probably be the definitive repository.
> 
> $ pypi install hello
> 
> is much better than
> 
> $ bluecheese install hello
> 

I have to say I prefer pypi myself.. I think it's a great idea
subtitling it 'cheeseshop' but referring to it directly as "cheeseshop"
is confusing at best. I've already had a few requests to change the text
of the link on the home page to 'packages' or 'package index'.

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


McMillan installer on solaris - complains about missing .pkg file

2006-03-10 Thread mrstephengross
I'm trying to get the mcmillan installer utility to generate a
standalone executable for me. I've gotten to work--almost!--but still
have one problem. After running Installer's Build.py on my script/spec,
it appears to work. I go into the directory generating by Build.py and
run my program. It works! Then I copy my program (foo) to a different
directory and try to run it there. It complains that: "Cannot open self
/home/sgross/foo or archive /home/sgross/foo.pkg". Do I have to
distribute the .pkg file with the executable? If so, is there a way
around this? I want to distribute a single, standalone executable.

Thanks,
--Steve ([EMAIL PROTECTED])

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


Re: Use python to process XML file

2006-03-10 Thread [EMAIL PROTECTED]
I have a little py module that implements the Composite pattern to
represent xml file contents. My class is called ExtensionRegistry
because that's what I use it for, you could rename it to whatever you
wanted. After parsing, this allows me to access my xml file contents
like this:

xmlFile = ExtensionRegistry(xmlFile = 'test.xml')

print xmlFile['log']['a'].getDataItems()

would result in printing

>>text

Let me know if you want me to send it to you.

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


Re: Python Evangelism

2006-03-10 Thread Andrew Gwozdziewycz
 > To emphasize the point as a newbie: I know what CPAN is. I would go to
> the Vaults of Parnassus for Python stuff. But Cheese Shop?
>

Well, why don't we promote it as PyPI (Python Package Index)? The url
_is_ python.org/pypi, and I'm pretty sure I read somewhere that PyPI
was the intended name... If the community then decides on some
standardized automated package management, I'm sure PyPI (cheese shop)
would probably be the definitive repository.

$ pypi install hello

is much better than

$ bluecheese install hello





--
Andrew Gwozdziewycz <[EMAIL PROTECTED]>
http://ihadagreatview.org
http://plasticandroid.org
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >