Re: Survey: improving the Python std lib docs

2017-05-22 Thread rzed
A portion of this thread seems to be focusing on what key word args parameters 
actually mean, in the Python sense. There is documentation for that, and a 
modicum of experience with Python makes this a relatively simple question and 
answer. However, when docs for a specific function or method specify keyword 
arguments without any indication of what the *expected* arguments might be, or 
what *useful* arguments might be, then it's not really helpful. If I have to 
look at the source code to figure out how the args are used, I don't need the 
docs at all. Which is why I suggest a line or two with sample invocations to 
provide at least a starting point to understand the parameters. 

A doc signature that says something like "do_something(p1, d)" tells me very 
little. Even knowing that p1 is a "Point" is not all that valuable, except to 
give me another item to look up (the expected Point implementation). However, 
an example like 'do_something((141,380),"January, 2017")' tells me a lot more - 
that the Point is actually a tuple with (probably) x-y coordinates, and 'd' is 
a description associated with that position. That's a lot of useful information 
at a cost of a couple of dozen characters. So why not add a few examples? 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Survey: improving the Python std lib docs

2017-05-16 Thread rzed
On Friday, May 12, 2017 at 6:02:58 AM UTC-4, Steve D'Aprano wrote:
> One of the more controversial aspects of the Python ecosystem is the Python
> docs. Some people love them, and some people hate them and describe them as
> horrible.
> 
[...]

One thing I would love to see in any function or class docs is a few example 
invocations, preferably non-trivial. If I need to see more, I can read the 
entire doc, but most times I just want a refresher on how the function is 
called. Does it use keywords? Are there required nameless parameters? In what 
order? A line or two would immediately clarify that most of the time. 

Apart from that, links to docs for uncommon functions (or to the docs of the 
module, if there are many) would be at least somewhat useful. 

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


Difficulty with ez_setup.py

2014-01-07 Thread Rzed
I am trying to run ez_setup.py on a fresh installation of Python 2.7.6 
in a Win XP environment, but I keep getting an error. Here's the traceback:


C:\Python27\Lib>python ez_setup.py
Extracting in c:\docume~1\dick\locals~1\temp\tmpkjidy0
Now working in c:\docume~1\dick\locals~1\temp\tmpkjidy0\setuptools-2.0.2
Installing Setuptools
Traceback (most recent call last):
  File "setup.py", line 17, in 
exec(init_file.read(), command_ns)
  File "", line 8, in 
  File 
"c:\docume~1\dick\locals~1\temp\tmpkjidy0\setuptools-2.0.2\setuptools\__init__.py", 
line 11, in 

from setuptools.extension import Extension
  File 
"c:\docume~1\dick\locals~1\temp\tmpkjidy0\setuptools-2.0.2\setuptools\extension.py", 
line 5, in 

from setuptools.dist import _get_unpatched
  File 
"c:\docume~1\dick\locals~1\temp\tmpkjidy0\setuptools-2.0.2\setuptools\dist.py", 
line 16, in 

import pkg_resources
  File 
"c:\docume~1\dick\locals~1\temp\tmpkjidy0\setuptools-2.0.2\pkg_resources.py", 
line 31, in 

from pkgutil import get_importer
ImportError: cannot import name get_importer
Something went wrong during the installation.
See the error message above.

It's been awhile since I last installed ez_install, and I remember it 
being a pain, but I don't remember this issue. What am I doing wrong?


On a possibly related note, is there a specific place that ez_setup.py 
is expected to be in when this is run?


--
rzed

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


Re: Python 3 syntax error question

2011-06-26 Thread rzed
steve+comp.lang.pyt...@pearwood.info wrote in
news:4e074768$0$29982$c3e8da3$54964...@news.astraweb.com: 

> rzed wrote:
> 
>> I've tried to install PySVG in a Python 3 setting, and I get a
>> few errors on the build. Most are easy to fix, but this one I
>> can't explain or fix:
>> 
>> 
>> Traceback (most recent call last):
>>   File "", line 1, in 
>>   File "builders.py", line 12, in 
>> from pysvg.shape import *
>>   File "C:\Python32\lib\site-packages\pysvg\shape.py", line 91
>> def moveToPoint(self,(x,y)):
>>  ^
>> SyntaxError: invalid syntax
>> 
> 
> Function signatures with automatic tuple-unpacking are no longer
> allowed in Python3. So functions or methods like this:
> 
> def moveToPoint(self,(x,y)):
> 
> have to be re-written with the tuple unpacking moved into the
> body of the function, e.g. something like this:
> 
> def moveToPoint(self, x_y):
> x, y = x_y
> 
> 
> Are you aware that you're trying to install a Python2 library
> under Python3? 
> 
> 

Thank you all for your responses. Yes, I am aware of the version 
difference, but not of all the implications of that. I will run this 
through 2to3, but even without doing that, there are only about four 
syntax errors, and the others were obvious and easily corrected. 

There does not seem to be a Py3 version of this package. I was hoping 
to try it to see what broke. Well, I found out at least part of that, 
didn't I?

I was not aware of the removal of tuple-unpacking. I expect there was 
some extensive conversation about that. 

As to 2to3, I have to say that:

-def a(b, (c,d)):
+def a(b, xxx_todo_changeme):
+(c,d) = xxx_todo_changeme

... is not terribly revealing if one is unaware of what about it 
needs changing. I know, I know: RTFM

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


Python 3 syntax error question

2011-06-26 Thread rzed
I've tried to install PySVG in a Python 3 setting, and I get a few 
errors on the build. Most are easy to fix, but this one I can't 
explain or fix:


Traceback (most recent call last):
  File "", line 1, in 
  File "builders.py", line 12, in 
from pysvg.shape import *
  File "C:\Python32\lib\site-packages\pysvg\shape.py", line 91
def moveToPoint(self,(x,y)):
 ^
SyntaxError: invalid syntax 


The moveToPoint method occurs three times in the file, with identical 
signatures. The other two are not showing up as errors, though since 
they occur later in the file, that may not be indicative. 

I don't see anything erroneous in this line. The syntax error often 
comes from the previous line, but I've moved this method around and 
it has always failed on this line and no other, regardless of what 
went before. 

I'm new to Py3, so maybe there's some obvious thing I'm not seeing 
here. Does anyone have any suggestions?

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


Re: ANN: PyGUI 2.5

2011-06-17 Thread rzed
Terry Reedy  wrote in 
news:mailman.88.1308338170.1164.python-l...@python.org:

> On 6/16/2011 11:18 PM, Greg Ewing wrote:
>> PyGUI 2.5 is available:
>>
>> http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/
>>
>> Lots of new stuff in this version. Highlights include:
> 
> Greg left out the most important to me:
> "Now works with Python 3 on MacOSX and Windows!"
> 

Apparently *only* Python 3 ?

C:\extracted\PyGUI-2.5>setup install
Traceback (most recent call last):
  File "C:\extracted\PyGUI-2.5\setup.py", line 12, in 
from distutils_extensions import pygui_build_py
ImportError: No module named distutils_extensions

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


Re: Python Card alternatives?

2011-06-13 Thread rzed
Wolfgang Keller  wrote in 
news:20110612191740.0de83e0e.felip...@gmx.net:

>> Are there any other, better solutions?
> 
> Others are e.g.:
> - Pypapi
> - Camelot
> - Kiwi
> - Sqlkit
> - Gnuenterprise
> etc...
> 
> Sincerely,
> 
> Wolfgang
> 

Many thanks to all of you for the interesting responses. As is so 
often the case with Python, there are many options, and many possible 
approaches to solutions for the same problem. I have some reading to 
do, I see.

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


Python Card alternatives?

2011-06-11 Thread rzed
Desktop apps don't seem to be the wave of the future, but they still 
serve a useful purpose today. They can be ideal for a quick database 
table management screen, or a data entry front end for a program with 
a bunch of parameters. It's not easy enough to build a quick utility 
with a GUI front end, though. Wax and PythonCard (and maybe others) 
tried to hit that niche, but development on both is spotty at best. 
Some claim that Dabo's gui builder is a good one for this purpose, and 
maybe it can be. Are there any other, better solutions?

I've been looking at Rebol lately, and it has some points of interest. 
I much prefer Python as a language, but Rebol View's layout 
specifications are wonderfully concise, and the support code seems to 
be fairly straightforward as well. Has anyone tried to mimic their 
approach in Python? 

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


Re: Parse config file and command-line arguments, to get a single collection of options

2011-05-28 Thread rzed
Ben Finney  wrote in
news:87k4deaxfc@benfinney.id.au: 

> Howdy all,
> 
> Python's standard library has modules for configuration file
> parsing (configparser) and command-line argument parsing
> (optparse, argparse). I want to write a program that does both,
> but also: 
> 
> * Has a cascade of options: default option values, overridden by
> config 
>   file options, overridden by command-line options.
> 
> * Reads a different, or even additional, configuration file if
> specified 
>   on the command-line (e.g. --config-file foo.conf) and yet still
>   obeys the above cascade.
> 
> * Allows a single definition of an option (e.g. logging level) to
> define 
>   the same option for parsing from configuration files and the
>   command line.
> 
> * Unifies the parsed options into a single collection for the
> rest of 
>   the program to access without caring where they came from.
> 
> How can I achieve this with minimum deviation from the Python
> standard library?
> 
> 
> (For anyone interested in gaining StackOverflow points, I'm also
> asking this as a question there so feel free to post answers on
> that site 
> http://stackoverflow.com/questions/6133517/parse-config-file-
> and-command-line-arguments-to-get-a-single-collection-of-optio>.) 
> 

This seems vaguely similar to a module I wrote and use all the time. 
It allows default value specification, categorization of command-line 
options, in-line parsing of further spec file[s] and overrides of 
values in the the sequence you define, pretty much. It doesn't deal 
with the "logging level" item. I'm not sure what that would mean. The  
idea of the module is to create a namespace object (though it could 
as easily be a dict) that contains whatever values are specified.

in the program it would be invoked like this:
ctx = Cmdline( outfname='test.out', size=(250,400), ... ) (or 
whatever).

The command line can contain switches, prefixed by hyphens, spec file 
names, prefixed by @, untagged names, or key=value pairs. The values 
will be parsed as (tuples), [lists], or {dicts}, ints, floats, or 
strings. I did not, I am ashamed to say, resist the temptation to 
guess. 'Ctx' will contain the result of all this. Switches, if any 
are in a list named ctx._switches, unadorned arguments are in a list 
named ctx._vars, and the other stuff is pretty much as you would 
expect. It expects configuration files to be in a sort of ini-file 
format. 

Here's an example:

---
test.spec:
log=test.log
count=10
size=(400,200)
group1={key=value,a=alpha}
group2={b=beta,name=doogie howser}
#
temp=[1,2,5,11,22]
sub=(al,becky,carl,diane,edwin,fran)

---
test.py:
from Cmdline import Cmdline
c = Cmdline( count=5, log='pink.tank')
c.show()

---
>python test.py log=friend.txt @test.spec count=32 name=waldo

... yields:
 count  = 32
 sub  = ('al', 'becky', 'carl', 'diane', 'edwin', 
'fran')
 log  = 'test.log'
 temp  = [1, 2, 5, 11, 22]
 group1  = {'a': 'alpha', 'key': 'value'}
 group2  = {'b': 'beta', 'name': 'doogie howser'}
 size  = (400, 200)
 name  = 'waldo'

... while

>python @test.spec count=32 name=waldo temp=Vitalis sub='' dream -k
 count  = 32
 _vars  = ['dream']
 log  = 'test.log'
 temp  = 'Vitalis'
 _switches  = ['k']
 name  = 'waldo'
 group1  = {'a': 'alpha', 'key': 'value'}
 group2  = {'b': 'beta', 'name': 'doogie howser'}
 size  = (400, 200)
 sub  = ''

What the program does with the results is up to it, of course.

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


Re: Purely historic question: VT200 text graphic programming

2011-03-13 Thread rzed
Anssi Saari  wrote in
news:vg3tyf75eq1@pepper.modeemi.fi: 

> rzed  writes:
> 
>> Did you say "was"? The last time I did any programming on a VMS
>> system was ... about 5 1/2 hours ago. Our shop runs OpenVMS now,
>> programs mostly in C and BASIC. I've quietly insinuated Python
>> into the mix over the last few months, and that has helped my
>> sanity considerably. 
> 
> I suppose I meant VMS running on VAX. I'd guess you run OpenVMS
> on Itanium these days?
> 
> 

Actually, on Alphas. We do have every intention of moving away from 
VMS, we keep saying. So hardware upgrades are not under consideration.

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


Re: Purely historic question: VT200 text graphic programming

2011-03-11 Thread rzed
Anssi Saari  wrote in
news:vg3hbba6mp7@pepper.modeemi.fi: 

> Grant Edwards  writes:
> 
>> C wasn't very widely used under VMS, and VMS had it's own screen
>> formatting and form handling libraries.
> 
> Just curious, what language was widely used in VMS? My VMS
> experience is limited to running Maple for a math course in the
> university in early 1990s. Didn't know how to do much more than
> start Maple, probably just dir, logout (or was it logoff?) and
> ftp :) 

Did you say "was"? The last time I did any programming on a VMS system 
was ... about 5 1/2 hours ago. Our shop runs OpenVMS now, programs 
mostly in C and BASIC. I've quietly insinuated Python into the mix 
over the last few months, and that has helped my sanity considerably.

I did use the curses library with Vax C years ago, though online data 
entry programs used the SMG library. 

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


Re: The Disappearing Program?

2010-02-20 Thread rzed
"W. eWatson"  wrote in
news:hlls5c$89...@news.eternal-september.org: 

> I've successfully compiled several small python programs on Win
> XP into executables using py2exe. A program goes from a name like
> snowball.py to snowball. A dir in the command prompt window finds
> snowball.py but not snowball. If I type in snowball, it executes.
> What's up with that? 

There is a ludicrous setting in Windows explorer that hides the 
extensions for known file types, such as .exe. If you see "snowball" 
in Win Explorer, that's probably the way your system is set. If you 
click on Tools . Folder Options . View you should see a checkbox for 
the "Hide extensions for known file types" option. Uncheck it, and the 
disappearing program will return to view.

This is a separate issue for why snowball.py executes when you enter 
"snowball" at the command line.

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


Re: Raw strings as input from File?

2009-12-01 Thread rzed
utabintarbo  wrote in
news:adc6c455-5616-471a-8b39-d7fdad217...@m33g2000vbi.googlegroups.c
om: 

> I have a log file with full Windows paths on a line. eg:
> K:\A\B\C\10xx\somerandomfilename.ext->/a1/b1/c1/10xx
> \somerandomfilename.ext ; txx; 11/23/2009 15:00:16 ;
> 1259006416 
> 
> As I try to pull in the line and process it, python changes the
> "\10" to a "\x08". This is before I can do anything with it. Is
> there a way to specify that incoming lines (say, when using
> .readlines() ) should be treated as raw strings?
> 
> TIA

Despite all the ragging you're getting, it is a pretty flakey thing 
that Python does in this context:
(from a python shell)
>>> x = '\1'
>>> x
'\x01'
>>> x = '\10'
>>> x
'\x08'

If you are pasting your string as a literal, then maybe it does the 
same. It still seems weird to me. I can accept that '\1' means x01, 
but \10 seems to be expanded to \010 and then translated from octal 
to get to x08. That's just strange. I'm sure it's documented 
somewhere, but it's not easy to search for.

Oh, and this:
>>> '\7'
'\x07'
>>> '\70'
'8'
... is realy odd.

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


Re: ANN: PyGUI 2.0.5

2009-04-26 Thread rzed
Greg Ewing  wrote in 
news:49f4278a.7010...@canterbury.ac.nz:

> PyGUI 2.0.5 is available:
> 
>http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/
> 
> More bug fixes for various platforms.
> 
> Still no idea what's causing the "object has been destroyed"
> error on Windows XP, though. Does this happen for everyone?
> Is there anyone who *has* got 12-scroll.py working for them
> on XP?

Works for me. I haven't seen an "object has been destroyed" error.

I note that 2.0.5 comments the WM_MOUSELEAVE event, which wasnt' 
mapped in Events.py. Does that mean there is no way to signal such an 
event? Is that a QT or PyQt limitation?

-- 
rzed
Groping nearsightedly through the MiaSma... 
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: PyGUI 2.0.4

2009-04-23 Thread rzed
David Robinow  wrote in
news:mailman.4403.1240449918.11746.python-l...@python.org: 

> On Wed, Apr 22, 2009 at 8:50 PM, rzed  wrote:
>> Greg Ewing  wrote in
>> news:49edb69f.7070...@canterbury.ac.nz:
>>
>>> PyGUI 2.0.4 is available:
>>>
>>>    http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/
>>>
[...]
>> I've always only gotten this response when I try to run the
>> blobedit demo:
>>  File "C:\extracted\PyGUI-2.0.4\Demos\BlobEdit\blobedit.py",
>> line 16, in 
>>    from GUI import Application, ScrollableView, Document,
>> Window, FileType, Cursor, rgb
>>  File "C:\Python25\Lib\site-packages\GUI\__init__.py", line 78,
>> in __getattr__
>>    traceback.print_stack()
>> Failed to import 'Application' from Applications
>> Traceback (most recent call last):
>>  File "C:\Python25\Lib\site-packages\GUI\__init__.py", line 69,
>> in __getattr__
>>    module = __import__(modname, self.__dict__, locals(), [name])
>> ImportError: No module named Applications
>>
>> I really don't know what this means. Is it a path issue? There
>> appears to be an Applications.py in GUI\Win32, with an
>> Application class. If there is some change I can make in the
>> code, can anyone tell me what to do? How can I fix it?
>>
[...]
>> --
>> rzed
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
> You probably have PyGTK for windows installed.  PyGUI tries
> "Cocoa", "Gtk", and "Win32" in that order.  You can override that
> by: 
> 
> SET PYGUI_IMPLEMENTATION=Win32
> 
> (This is rather awkward.  Perhaps "Win32" should be tried before
> "Gtk"? ) 

Thank you VERY much for an excellent diagnosis and prescription. This 
does get beyond that frustrating barrier. 

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


Re: ANN: PyGUI 2.0.4

2009-04-22 Thread rzed
Greg Ewing  wrote in 
news:49edb69f.7070...@canterbury.ac.nz:

> PyGUI 2.0.4 is available:
> 
>http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/
> 
> Fixes a few more bugs and hopefully improves things
> on Windows, although I can't be sure it will fix all
> the Windows problems people are having, because I
> haven't been able to reproduce some of them.

I want PyGUI to work so badly that it just kills me to find that 
that's how it works for me. So badly.

I've always only gotten this response when I try to run the blobedit 
demo:
  File "C:\extracted\PyGUI-2.0.4\Demos\BlobEdit\blobedit.py", line 
16, in 
from GUI import Application, ScrollableView, Document, Window, 
FileType, Cursor, rgb
  File "C:\Python25\Lib\site-packages\GUI\__init__.py", line 78, in 
__getattr__
traceback.print_stack()
Failed to import 'Application' from Applications
Traceback (most recent call last):
  File "C:\Python25\Lib\site-packages\GUI\__init__.py", line 69, in 
__getattr__
module = __import__(modname, self.__dict__, locals(), [name])
ImportError: No module named Applications

I really don't know what this means. Is it a path issue? There 
appears to be an Applications.py in GUI\Win32, with an Application 
class. If there is some change I can make in the code, can anyone 
tell me what to do? How can I fix it? 

The thing is, in my opinion, something like this is what Python 
*should* have in its standard package. That is, a PYTHON GUI, not a 
thin wrapper around an application-specific API. Sure, the GUI is in 
fact a wrapper, but it should not matter what the back end is that 
supports it (eventually... I know, baby steps). 

Obviously, I don't know from GUIs, or maybe it would be obvious to me 
what to do to get it working. And it is for people like me that I 
want to see it work. I really don't want to have to spend more than a 
few minutes investigating the nuances of a windowing system. I just 
want to be able to put up a convenient front end for a program. 

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


Re: Rough draft: Proposed format specifier for a thousands separator

2009-03-22 Thread rzed
Raymond Hettinger  wrote in
news:e35271b9-7623-4845-bcb9-d8c33971f...@w24g2000prd.googlegroups.c
om: 

> If anyone here is interested, here is a proposal I posted on the
> python-ideas list.
> 
> The idea is to make numbering formatting a little easier with the
> new format() builtin
> in Py2.6 and Py3.0: 
> http://docs.python.org/library/string.html#formatspec 
> 
[...]
> Comments and suggestions are welcome but I draw the line at
> supporting Mayan numbering conventions ;-)

Is that inclusive or exclusive?

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


Re: Scanning a file character by character

2009-02-22 Thread rzed
Spacebar265  wrote in
news:c86cd530-cee5-4de6-8e19-304c664c9...@c12g2000yqj.googlegroups.c
om: 

> On Feb 11, 1:06 am, Duncan Booth 
> wrote: 
[...]
>> >>> re.split("(\w+)", "The quick brown fox jumps, and falls
>> >>> over.")[1::2] 
>>
>> ['The', 'quick', 'brown', 'fox', 'jumps', 'and', 'falls',
>> 'over'] 
> 
> Using this code how would it load each word into a temporary
> variable. 

>>> import re
>>> list_name = re.split("(\w+)", "The quick brown fox jumps, and 
falls over.")[1::2]
>>> list_name[2]
'brown'

You see, temporary variables are set. Their names are spelled 
'list_name[x]', where x is an index into the list. If your plan was 
instead to have predefined names of variables, what would they be 
called? How many would you have? With list variables, you will have 
enough, and you will know their names.

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


Re: Import, site packages, my modules, Windows vs. Linux

2008-06-07 Thread rzed
John Ladasky <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]
com: 

> Hi folks,
> 
> Running Python 2.5 on both a Windows XP laptop, and an Ubuntu
> Linux 7.04 desktop.
> 
> I've gotten tired of maintaining multiple copies of my personal
> modules that I use over and over.  I have copies of these files
> in the same directory as the main program I happen to be working
> on at the time.  I've also downloaded FANN, and want to use its
> Python bindings.  FANN does not seem to build automatically,
> like wxWidgets did.
> 
> These two issues have led me to examine exactly how the import
> statement works, how the PYTHONPATH environment variable is
> constructed, and how to change it.
> 
> On Windows I found a solution that works, but which may be a
> kludge. In the Python "site-packages" folder, I added a
> sub-folder called "my- packages".  Then I created a text file,
> "my-packages.pth", containing the single line, "my-packages." 
> Finally, I moved my common personal modules into the my-packages
> folder and deleted all of my clumsy duplicates.  Import
> statements now work for all of my files on the Windows box,
> great! 
> 
> I then tried to use this same strategy in Linux, and saw that I
> don't automatically have the privileges needed to alter the
> site-packages folder.  On my Windows box, my default account has
> Administrator privileges.  On Linux I can, of course, use sudo
> to modify the site- packages folder.  But the fact that I would
> have to use sudo has me asking -- is there something
> inappropriate, or unsafe in my approach? 
> 
> I want to know what is the *recommended* way to integrate my own
> personal modules with Python.  Thanks!

I can't speak about Linux, but on Windows, you really should move 
your code out of the Python directory tree, I believe. When you 
upgrade, you'll have to be sure to set it up the same way again, 
and remember that your code resides there before you wipe out that 
directory tree, etc. 

Instead, just set up another directory containing your code and add 
that to your PYTHONPATH environment variable string. That will be 
unaffected by the Python version you're running, and will be 
available for multiple versions, if you run more than one.

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


Re: Doesn't know what it wants

2008-01-26 Thread rzed
Tim Rau <[EMAIL PROTECTED]> wrote in
news:0104616d-87be-4250-b3ef-
[EMAIL PROTECTED]
com: 

> On Jan 26, 1:41 am, John Machin <[EMAIL PROTECTED]> wrote:
>> On Jan 26, 4:20 pm, Tim Rau <[EMAIL PROTECTED]> wrote:
>>
>>
>>
>> > Traceback (most recent call last):
>> >   File "C:\Documents and Settings\Owner\My Documents\NIm's
>> >   code\sandbox 
>> > \sandbox.py", line 242, in 
>> > player = ship()
>> >   File "C:\Documents and Settings\Owner\My Documents\NIm's
>> >   code\sandbox 
>> > \sandbox.py", line 121, in __init__
>> > self.phyInit()
>> >   File "C:\Documents and Settings\Owner\My Documents\NIm's
>> >   code\sandbox 
>> > \sandbox.py", line 147, in phyInit
>> > moi = cp.cpMomentForCircle(self.mass, .2, 0,
>> > vec2d((0,0))) 
>> > ArgumentError: argument 4: :
>> > expected vec2d instance instead of vec2d
>>
>> > As far as I can tell, It's getting a vec2d, and it wants a
>> > vec2d. I't seems like it doesn't know what it wants, but I
>> > thought only teenagers did that, no programming languages.
>>
>> It possibly means that it is expecting an instance of a class
>> whose name is "vec2d"  but you have given it an instance of
>> some *other* class whose name just happens to be "vec2d".
>>
>> > clearly, Im missing something.
>>
>> Yes, some information:
>> 1. what is vec2d, class or function?
>> 2. what do you believe vec2d((0, 0)) should return?
>> 3. what is this belief based on?
>> 4. what has it actually returned this time?
>> 5. what do you believe that cp.cpMomentForCircle expects as
>> argument 4?
>> 6. what is this belief based on?
>>
>> The ArgumentError exception is raised by ctypes "when a foreign
>> function call cannot convert one of the passed arguments".
>> Based on guessin'n'googlin' the cp thing is a set of Python
>> bindings to a library written in C++ ... have you considered
>> asking the author of the bindings?
> 
> 1. vec2d is a class, designed to hold and manipulte 2d vectors
> 2. it should return a vector with x=0 and y=0
> 3. That's what it's done before.
> 4. trying it in the interpreter seems to show that it returns a
> vec2d with zero length. as it should.
> 5.cp.cpMomentForCircle seems to expect a vec2d. I'm baseing that
> on a functioning demo that uses the exact same line.
> 
> I guess that the vec2d I've got is not the one it wants. How do
> I tell the difference? I'll go look at all the imports.
> 

Are you passing the class or an instance of the class? I'd bet the 
former, but it should be the latter.

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


Re: may be a bug in string.rstrip

2007-11-22 Thread rzed
"kyo guan" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Hi :
> 
>  Please look at this code: 
> 
>>>> 'exe.torrent'.rstrip('.torrent')
> 'ex'   <-  it should be 'exe', why?

It really shouldn't be.

> 
> but this is a right answer:
> 
>>>> '120.exe'.rstrip('.exe')
> '120'   <-- this is a right value.
> 
>  there is a bug in the rstrip, lstrip there isn't this
>  problem. 

It's not a bug, but a misunderstanding of the way the function
works.  

The argument you pass to strip, lstrip or rstrip is a character or
collection of characters to trim from the end of a string. You
would get the same results from: "120.exe".rstrip('.ex') or
"120.exe".rstrip('x.e') or
"120.exe".rstrip('ab.cdefghijklmnopqrstuvwxyz')

In other words, by passing ".torrent" as an argument, you cause
the function to remove and of the characters in this set: [.toren]
from the end of the string. Not surprisingly, it did remove
".torrent", but also the trailing 'e' from 'exe'. Since 'x' is not
in that set of characters, the function stopped there. 

-- 
rzed

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


Re: What is python?????

2007-11-19 Thread rzed
James Stroud <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> 
> You're having a conversation with a spambot.

Actually, my intent was to address the question that was asked. 
Much of the genuine conversation in the group really does intermix 
the various senses of "Python", sometimes in ways that confuse the 
issues actually being discussed. People ask for changes to the 
language syntax when what they are really after can be addressed 
by additions or changes to libraries. Or they believe Python 
should have such-and-such a feature when the feature is available 
through external packages. Or their suggested changes to 
accommodate their desired feature would require fundamental and 
incompatible changes to the compiler.

The way I think of the language Python is as a clean, small 
enabler of functionality. The prepackaged Python distro supplies 
some of that functionality (the included batteries), and the 
environment Python makes far more available. Under that view, 
changes to the language should be the sort that allow the 
functionality to proceed cleanly. That is, there should be a 
Pythonic way to approach databases, windowing, interprocess 
communication and so on. The packages that perform the function 
should be interchangeable as far as the language is concerned. I 
don't believe everyone here would agree with this view, possibly. 

Regardless of the origin of the question, though, it is one worth 
discussing, which is why I responded to the post. Do we all really 
have the same view of what Python actually is? Or what it could 
be?

-- 
rzed


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


Re: What is python?????

2007-11-18 Thread rzed
Cope <[EMAIL PROTECTED]> wrote in news:7ab5b781-3c6c-
[EMAIL PROTECTED]:

> please tell me what is python.This group is so crowded.
> 

I see nobody has chosen to answer your question seriously. I'll 
give you an answer, but it is probably not to the question you are 
asking, either.

Python is not one thing.

Python is the name of a computer language, which you can determine 
easily through Google or Wikipedia or other means. That's what 
comp(uter).lang(uage).python is here for, nominally.

Python is also a package of programs that implement the language 
and create a Python runtime environment. The most common 
implementation is of a virtual machine that runs Python bytecodes, 
though other variations run Java or .NET bytecodes.

And Python is also a set of packages that provide utilities and 
features that allow users of the packages to do useful things on 
their computers without unnecessary fuss and bother. Some of these 
utilities come with a basic Python installation (code name: 
"batteries included"), while others are available elsewhere, often 
from the Python Package Index (codename: "cheese shop"), but from 
other sources as well. 

Some people conflate these meanings of "Python", which can lead to 
confusion at times. Much of the crowdedness of the group has to do 
with discussion related to the batteries-included features and to 
the other packages written to run in the Python environment.

Hope that helps.

-- 
rzed


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


Re: startswith( prefix[, start[, end]]) Query

2007-09-08 Thread rzed
Duncan Booth <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

I went through your example to get timings for my machine, and I 
ran into an issue I didn't expect.

My bat file did the following 10 times in a row:
(the command line wraps in this post)

call timeit -s "s='abracadabra1'*1000;t='abracadabra2';
startswith=s.startswith" startswith(t)
... giving me these times:

100 loops, best of 3: 0.483 usec per loop
100 loops, best of 3: 0.49 usec per loop
100 loops, best of 3: 0.489 usec per loop
100 loops, best of 3: 0.491 usec per loop
100 loops, best of 3: 0.488 usec per loop
100 loops, best of 3: 0.492 usec per loop
100 loops, best of 3: 0.49 usec per loop
100 loops, best of 3: 0.493 usec per loop
100 loops, best of 3: 0.486 usec per loop
100 loops, best of 3: 0.489 usec per loop

Then I thought that a shorter name for the lookup might affect the 
timings, so I changed the bat file, which now did the following 10 
times in a row:

timeit -s "s='abracadabra1'* 1000;t='abracadabra2';
sw=s.startswith" sw(t)

... giving me these times:
100 loops, best of 3: 0.516 usec per loop
100 loops, best of 3: 0.512 usec per loop
100 loops, best of 3: 0.514 usec per loop
100 loops, best of 3: 0.517 usec per loop
100 loops, best of 3: 0.515 usec per loop
100 loops, best of 3: 0.518 usec per loop
100 loops, best of 3: 0.523 usec per loop
100 loops, best of 3: 0.513 usec per loop
100 loops, best of 3: 0.514 usec per loop
100 loops, best of 3: 0.515 usec per loop

In other words, the shorter name did seem to affect the timings, 
but in a negative way. Why it would actually change at all is 
beyond me, but it is consistently this way on my machine. 

Can anyone explain this?

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


Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers

2007-09-02 Thread rzed
[EMAIL PROTECTED] wrote in
news:[EMAIL PROTECTED]: 

> The puzzle is: p is the perimeter of a right angle triangle with
> integral length sides, {a,b,c}. which value of p  < 1000, is the
> number of solutions {a,b,c} maximised?
> 
> Here's my python code:
> 
> #!/usr/local/bin/python
> 
> solutions = [0] * 1001
> p = 0
> 
> for a in xrange(1, 1000):
> for b in xrange(1, 1000 - a):
> for c in xrange(1, 1000 - a - b):
> p = a + b + c
> if p < 1000:
> if a ** 2 + b ** 2 == c ** 2:
> solutions[p] += 1
>

Once p >= 1000, it ain't goin' back. If you break out of the 
innermost loop here after that happens, you'll save a bunch of 
time.
 
> max = 0
> maxIndex = 0
> index = 0
> for solution in solutions:
> if solution > max:
> max = solution
> maxIndex = index
> index += 1
> 
> print maxIndex
> 
> 
> It takes 2 minutes and twelve seconds on a 2.4GHz Core2Duo
> MacBook Pro.
>
[...]
 
> The resulting executable takes 0.24 seconds to run. I'm not
> expecting a scripting language to run faster than native code,
> but I was surprised at how much slower it was in this case. Any
> ideas as to what is causing python so much trouble in the above
> code? 
> 

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


Re: SimplePrograms challenge

2007-06-14 Thread rzed
Steven Bethard <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Steve Howell wrote:
>> --- George Sakkis <[EMAIL PROTECTED]> wrote:
>>> from itertools import count, ifilter
>>> def sieve():
>>> seq = count(2)
>>> while True:
>>> p = seq.next()
>>> seq = ifilter(p.__rmod__, seq)
>>> yield p
> [snip]
>> Is there a way to broaden the problem somehow, so that
>> it can be a longer solution and further down on the
>> page, and so that I can continue to enforce my
>> somewhat arbitrary rule of ordering examples by how
>> long they are?
> 
> How about we just comment it better?
> 
> import itertools
> 
> def iter_primes():
>  # an iterator of all numbers between 2 and +infinity
>  numbers = itertools.count(2)
> 
>  # generate primes forever
>  while True
> 
>  # generate the first number from the iterator,
>  # which should always be a prime
>  prime = numbers.next()
>  yield prime
> 
>  # lazily remove all numbers from the iterator that
>  # are divisible by prime we just selected
>  numbers = itertools.ifilter(prime.__rmod__, numbers)
> 
> I think that's 17-ish, though you could shrink it down by
> removing some of the spaces.
> 
> STeVe

How about including a driver? Generators are frustrating for 
newbies (including oldies new to generators) because they don't 
actually do anything unless you know how to use them. Given the 
above, what's a newbie going to try first? Something like:

>>> iter_primes()

Hmmm. Doesn't do anything.

How about 
>>> for ix in range(10):
... print iter_primes()

Not what you might expect.

Later:

>>> for ix in range(10):
... print iter_primes().next()

Hm

... and so on.

In much of Python's documentation, and in this case, an occasional 
working example of use would go FAR in aiding understanding of the 
underlying concept.

-- 
rzed

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


Re: Python and GUI

2007-05-26 Thread rzed
Brian Blais <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

[...]

> Finally, consider wax (http://zephyrfalcon.org/labs/wax.html). 
> In my view, this is *exactly* what python needs, and its not
> being maintained anymore as far as I can tell.  What I like
> about it is: 
> 
> 1) it is small...I can include the entire wax distribution in my
> app with only a 780k 
>   footprint.
> 2) it is a very thin layer on wx, so when something doesn't
> quite work, I can immediately fall back onto wx, mixing and
> matching wax and wx objects.  it's just that the wax objects
> have more pythonic calling and use properties 
> 
> 
> Is there a reason that the port of wxPython doesn't include wax,
> or something similar?  It would seem pretty straightforward,
> when porting the wx to Python, to simply include such a wrapper.
>  I wish I were more clever, and had more time, to take over the
> maintenance of wax because I think it is the most
> straightforward, practical, and pythonic solution out there.
> 
> 
> Do others think like me here?
> 

I certainly do. Whether wax is the particular solution or not, 
something very like it should be. Something like this was tried at 
one time (Anygui) and the general consensus seems to be that it 
doesn't work as an approach because the packages are too 
different. I think that it's past time to revisit that conclusion. 

It would be very useful to a user of the Language we call Python 
to be able to write GUI code without regard to the back-end 
package. If there were a standard Python GUI API (call it the PGA, 
say) that be the target for app developers, they wouldn't have to 
worry about the back end. The PGA would have to be flexible enough 
to handle incompatibilities among the various approaches to 
displaying widgets and text. In order for that to happen, some 
kind of meeting of minds (among those who now deal with the murky 
middle between gui packages and python) would have to take place. 
A standard would have to be hammered out and then used. 

The standard would have to allow for generic calls for tasks that 
any reasonable GUI would have to handle. It would also have to 
provide for system-specific calls for those things that each 
package might require uniquely. The interface to the system-
specific stuff should itself be the same regardless of the back 
end. What I mean by this is that, where wax's limitations are 
overcome by dropping to wx directly, there should instead by a PGA 
winsys() call that permits passing command strings, values, or 
whatever in a dict-like object that would be permit the pga2wx 
interface to create the specific calls it needs. When the back end 
changes to Qt, the pga2Qt interface would make the translation 
instead. The code from the app programmer should not have to 
change, except maybe to add another item or items to the winsys 
dict.

I also think there should something similar for an interface for 
Python database access (PDBA). Anydb might not be the solution, 
but it could be. It would take cleverness (which abounds in the 
Python community),  determination (which may not be in such 
abundance) and project coordination for either of these projects 
to come to fruition. A summer of code kind of thing would provide 
a good initial push, and some sprints could move things along at a 
good clip. Wax, anygui, and anydb seem to be acceptable starting 
points, but the key thing is to get agreement from key players 
(like the developers of wxPython, dabo, PythonCard, and so on) to 
agree that this is a good direction to go in, and to try to work 
out the requirements for a flexible PGA and PDBA. I'm sure that 
the approach could produce usable results in short order, and then 
attack the remaining limitations over time.

Do I think this is going to happen? No. 

There are two overlapping things we call Python: the Language and 
the Package. The Language comes from Guido and a few others, but 
the Package comes from many sources, mostly volunteers. The GUI 
interfaces come from many such sources, each with a different view 
of what constitutes a good Pythonic interface. Having put a lot of 
time and effort into getting their version up and running, they're 
not about to change for some abstract reason, but nonetheless, I 
do believe that the Language of Python should have a GUI API 
defined, and that the Package of Python should accommodate to 
that. Unless that happens, we'll see more of what we now see: 
continual questions about what is the best GUI or the best 
Database. Because once you start building an app, you commit to 
the syntax of the package and you are no longer (in my view) 
coding in Python, but in that subset that includes the GUI Package 
of your choice.

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


Re: Printing dots in sequence ('...')

2007-05-22 Thread rzed
"Tim Williams" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

[...]

> maybe this:   (on Win32, don't know about *nix)
> 
> for x in range(10):
>   print '.\b',

better:
print '\b.',

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


Re: Lists vs tuples (newbie)

2007-05-21 Thread rzed
Szabolcs <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> 
> I was wondering about why are there both tuples and lists? Is
> there anything I can do with a tuple that I cannot do with a
> list? 
> 
> In what circumstances is it advantageous to use tuples instead
> of lists? Is there a difference in performance?
> 
> I am still learning Python, so please be gentle ...
> 
This topic comes up from time to time in this newsgroup. If you want 
a lot of viewpoints about it, Google is your friend. 

A short answer, though: tuples can be used as dictionary keys and 
lists cannot. I would guess (but would have to test to confirm) that 
tuples occupy less space for the same data. I don't know whether any 
differences in, say, iteration speed would be terribly significant, 
but I would expect tuples to be marginally faster. 

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


Re: Nested dictionaries trouble

2007-04-21 Thread rzed
IamIan <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Thank you again for the great suggestions. I have one final
> question about creating a httpMonths dictionary like {'Jan':'01'
> , 'Feb':'02' , etc} with a minimal amount of typing. My code
> follows (using Python 2.3.4):
> 
> import calendar
> 
> # Create years list, formatting as strings
> years = map(str, xrange(1990,2051))
> 
> # Create months list with three letter abbreviations
> months = list(calendar.month_abbr)
> 
> # Create monthTotals dictionary with default value of zero
> monthTotals = dict.fromkeys(months[1:],0)
> 
> # Create yearTotals dictionary with years for keys
> # and copies of the monthTotals dictionary for values
> yearTotals = dict([(year, monthTotals.copy()) for year in
> years]) 
> 
> # Create httpMonths dictionary to map month abbreviations
> # to Apache numeric month representations
> httpMonths =
> {"Jan":"01","Feb":"02","Mar":"03","Apr":"04","May":"05","Jun":"0
6
> ","Jul":"07","Aug":"08","Sep":"09","Oct":"10","Nov":"11","Dec":"
1
> 2"} 
> 
> It is this last step I'm referring to. I got close with:
> httpMonths = {}
> for month in months[1:]:
>   httpMonths[month] = str(len(httpMonths)+1)
> 
> but the month numbers are missing the leading zero for 01-09.
> Thanks! 
> 

Maybe something like: 
httpMonths = dict((k,"%02d" % (x+1)) 
for x,k in enumerate(months[1:]) )

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


Re: Clean "Durty" strings

2007-04-02 Thread rzed
"Diez B. Roggisch" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

>> 
>> If the OP is constrained to standard libraries, then it may be
>> a question of defining what should be done more clearly. The
>> extraneous spaces can be removed by tokenizing the string and
>> rejoining the tokens. Replacing portions of a string with
>> equivalents is standard stuff. It might be preferable to create
>> a function that will accept lists of from and to strings and
>> translate the entire string by successively applying the
>> replacements. From what I've seen so far, that would be all the
>> OP needs for this task. It might take a half- dozen lines of
>> code, plus the from/to table definition. 
> 
> The OP had -tags in his text. Which is _more_ than a half
> dozen lines of code to clean up. Because your simple
> replacement-approach won't help here: 
> 
> foo  bar 
> 
> Which is perfectly legal HTML, but nasty to parse.

Well, as I said, given the input the OP supplied, it's not even 
necessary to parse it. It isn't clear what the true desired 
operation is, but this seems to meet the criteria given:


s ="""\
bonne mentalité mec!:) \nbon 
pour
info moi je suis un serial posteur arceleur dictateur ^^*
\nmais pour avoir des resultats 
probant il
faut pas faire les mariolles, comme le "fondateur" de 
bvs
krew \n
mais pour avoir des resultats probant il faut pas faire les 
mariolles,
comme le "fondateur" de bvs krew \n"""

fromlist = ['', 'é', '"']
tolist   = ['', 'é', '"' ]


def withReplacements( s, flist,tlist ):
for ix, f in enumerate(flist):
t = tlist[ix]
s = s.replace( f,t )
return s

print withReplacements(' '.join(s.split()),fromlist,tolist)



If the question is about efficiency or robustness or generality, 
then that's another set of issues, but that's for the 1.1 version 
to handle. 

-- 
rzed

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

Re: Clean "Durty" strings

2007-04-02 Thread rzed
"Diez B. Roggisch" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Ulysse wrote:
> 
>> Hello,
>> 
>> I need to clean the string like this :
>> 
>> string =
>> """
>> bonne mentalité mec!:) \nbon
>> pour info moi je suis un serial posteur arceleur dictateur ^^*
>> \nmais pour avoir des resultats
>> probant il faut pas faire les mariolles, comme le
>> "fondateur" de bvs krew \n
>> mais pour avoir des resultats probant il faut pas faire les
>> mariolles, comme le "fondateur" de bvs krew \n
>> """
>> 
>> into :
>> bonne mentalité mec!:) bon pour info moi je suis un serial
>> posteur arceleur dictateur ^^* mais pour avoir des resultats
>> probant il faut pas faire les mariolles, comme le "fondateur"
>> de bvs krew mais pour avoir des resultats probant il faut pas
>> faire les mariolles, comme le "fondateur" de bvs krew
> 
> The obvious way that has been suggested to you at other places
> is to use BeautifulSoup.
>  
>> To do this I wold like to use only strandard librairies.
> 
> Then you need to reprogram what BeautifulSoup does. Happy
> hacking! 
> 

If the OP is constrained to standard libraries, then it may be a 
question of defining what should be done more clearly. The extraneous 
spaces can be removed by tokenizing the string and rejoining the 
tokens. Replacing portions of a string with equivalents is standard 
stuff. It might be preferable to create a function that will accept 
lists of from and to strings and translate the entire string by 
successively applying the replacements. From what I've seen so far, 
that would be all the OP needs for this task. It might take a half-
dozen lines of code, plus the from/to table definition.

-- 
rzed

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

Re: print a ... z, A ... Z, "\n"' in Python

2007-03-03 Thread rzed
[EMAIL PROTECTED] (Alex Martelli) wrote in
news:[EMAIL PROTECTED]: 

> js  <[EMAIL PROTECTED]> wrote:
> 
>> HI guys,
>> 
>> How do you write Perl's
>> 
>> print a ... z, A ... Z,  "\n"' in Python
>> 
>> In Python?
> 
> This specific one is easy, though this doesn't generalize:
> 
> import string
> print string.lowercase + string.uppercase
> 
> For the general case, there's no way to avoid calling chr and
> ord, because a string in Python doesn't have a "natural
> successor". So the only issue is how you prefer to hide those
> calls &c (in some class or function) and you already received
> suggestions on that. 
> 

No ord or chr in sight:

# Inclusive character range. 
def pycrange(lo,hi):
import string
chars = string.letters + " "
rstr = ''
lp = chars.find(lo)
hp = chars.find(hi)
if lp < hp:
rstr = chars[lp:hp+1]
return rstr

print pycrange('c','n')


Lame code, though.

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


Re: quickly read a formated file?

2007-03-01 Thread rzed
[EMAIL PROTECTED] wrote in
news:[EMAIL PROTECTED]: 

> lialie:
>> The formated file may be very popularly, but the module
>> ConfigPaser doesn't handle it. Is there a way to process it
>> freely? 
> 
> First try, assuming the input file can be read whole. The code
> isn't much readable, it needs better variable names (name
> names?), comments, etc.
> 
> data = """
> %HEADER
> title1 = "Untilted1"
> username = "User1"
> 
> %DATA
> title2 = "Untilted2"
> username2 = "User2"
> """
> 
> l1 = (p.strip().splitlines() for p in data.split("%") if
> p.strip()) result = {}
> for part in l1:
> pairs1 = (pair.split('=') for pair in part[1:])
> pairs2 = ((k.strip(), v.strip().strip('"')) for k,v in 
pairs1) result[part[0]] = dict(pairs2)
> print result
> 
> 

If there could be embedded perecent signs in the data, that will 
produce some unexpected results, though. Here's another shot:

data = """
%HEADER
title1 = "Untilted1"
username = "User1"

%DATA
title2 = "The 7% Solution"
username2 = "User2"
"""

# Assumes there may be embedded percent signs in data
# and all data lines are of the form key = value
def parseData(data):
pd = {}
idata = iter(data)
for line in idata:
line = line.strip()
if line.startswith('%'):
tname = line[1:]
cd = pd[tname] = {}
line = idata.next().strip()
while line != '':
if line.find('=') > 0:
id,val = line.split('=',1)
cd[id.strip()] = val.strip().strip('"')
line = idata.next().strip()
return pd


print parseData(data.split('\n'))

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


Re: Dividing integers...Convert to float first?

2007-02-04 Thread rzed
"Simon Brunning" <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

> On 1/5/07, Grant Edwards <[EMAIL PROTECTED]> wrote:
>>>>> from __future__ import LotteryNumbers
>>  File "", line 1
>>SyntaxError: future feature LotteryNumbers is not defined
>>
>> Damn.
>>
>> I guess it's back to work then.
> 
> Remember the PEP 8 module name standards.
> 
>>>> from __future__ import lottery_numbers
> [1, 16, 19, 20, 21, 39]
> 

My Python version is so old that I only get three numbers. I guess 
I'll have to upgrade.

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


Re: Parameter lists

2007-02-04 Thread rzed
Mizipzor <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Consider the following snippet of code:
> 
> ==
> 
> class Stats:
> def __init__(self, speed, maxHp, armor, strength,
> attackSpeed, imagePath): 
> self.speed = speed
> self.maxHp = maxHp
> self.armor = armor
> self.strength = strength
> self.attackSpeed = attackSpeed
> self.originalImage = loadTexture(imagePath)
> 
> ==
> 
> I little container for holding the stats for some rpg character
> or something. Now, I dont like the looks of that code, there are
> many function parameters to be sent in and if I were to add an
> attribute, i would need to add it in three places. Add it to the
> function parameters, add it to the class and assign it.
> 
> Is there a smoother way to do this? There usually is in python,
> hehe. I recall when reading python tutorials that you could do
> something like this:
> 
> foo(*list_of_parameters):
> 
> To send many parameters as a list or a tuple. Then I could
> assign them like this:
> 
> class Stats:
> def __init__(self, *li):
> self.speed = li[0]
> self.maxHp = li[1]
> (...)
> 
> Or maybe there is an even niftier way that lets me iterate
> through them? Hmm... but that may lead to that I need to store
> them in a way that makes it cumbersome to access them later.
> 
> Any comments and/or suggestions are welcome!  :)
> 

I often use something like this, based on a Martellibot posting:

>>> class Stats(dict):
... def __init__(self, *args, **kwds):
... self.update(*args)
... self.update(kwds)
... def __setitem__(self, key, value):
... return super(Stats, self).__setitem__(key, value)
... def __getitem__(self, name):
... try:
... return super(Stats, self).__getitem__(name)
... except KeyError:
... return None
... __getattr__ = __getitem__
...     __setattr__ = __setitem__
...
>>> m = dict(a=1,b=22,c=(1,2,3))
>>> p = Stats(m,x=4,y=[5,9,11])
>>> p.y
[5, 9, 11]
>>> p['y']
[5, 9, 11]

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


Re: strange test for None

2007-02-03 Thread rzed
"karoly.kiripolszky" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> in my server i use the following piece of code:
> 
> ims = self.headers["if-modified-since"]
> if ims != None:
> t = int(ims)
> 
> and i'm always getting the following error:
> 
> t = int(ims)
> ValueError: invalid literal for int(): None
> 
> i wanna know what the hell is going on... first i tried to test
> using is not None, but it makes no difference.
> 

It appears that ims is the string 'None', so it fails the test, but 
is an invalid literal.

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


Re: How do I print out in the standard output coloured lines

2007-02-02 Thread rzed
[EMAIL PROTECTED] wrote in
news:[EMAIL PROTECTED]: 

> On Feb 2, 1:16 pm, rzed <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] wrote
>> innews:[EMAIL PROTECTED]: 
>>
>> > Hi,
>>
>> >   I'm interested in printing out coloured lines of my
>> >   application and
>> > I don't know what to use. Can anybody give me an idea??
>>
>> You could speed up the process if you explain what your
>> application is and what you mean by colored lines. Does your
>> application emit output to a plotter, an ink-jet printer, or a
>> color laser printer? Is it a drawing program? An editor in
>> which you want lines colored to highlight context? It might be
>> useful to know what system you are running as well. Just a
>> little detail here. 
>>
>> --
>> rzed
> 
> Well, yes, it's a program that prints out lines to the standard
> output with a print command, and I want to print them coloured.
> For example: 
> 
> print "Hello World!!"
> 
> I want it in red colour.
> 
> That's all.
> 
> 

If you're on Linux, you could use the curses module. There may be 
a precompiled Windows version compatible with your Python version, 
or maybe not, but the Windows source is available, and you may be 
able to get it to work with your Python with some effort. Linux 
distros include curses, I think. For Windows curses, take a look 
at <http://adamv.com/dev/python/curses/>. You will understand why 
the phrase "Windows curses" is used, I expect. 

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


Re: How do I print out in the standard output coloured lines

2007-02-02 Thread rzed
[EMAIL PROTECTED] wrote in
news:[EMAIL PROTECTED]: 

> Hi,
> 
>   I'm interested in printing out coloured lines of my
>   application and 
> I don't know what to use. Can anybody give me an idea??
> 

You could speed up the process if you explain what your application 
is and what you mean by colored lines. Does your application emit 
output to a plotter, an ink-jet printer, or a color laser printer? Is 
it a drawing program? An editor in which you want lines colored to 
highlight context? It might be useful to know what system you are 
running as well. Just a little detail here.

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


Re: win32com.client

2007-02-01 Thread rzed
"vithi" <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

> Hi,
> I use python for window. If you are saying win32com in part of 
the
> python then you are wrong.

That is not what I or anyone else is saying. What we have said, 
perhaps not in words you understand, is this:

1) In your browser, enter this URL: 
http://sourceforge.net/projects/pywin32/

2) When the page comes up, find the big green box that says 
"Download Python for Windows extensions" and click on it

3) In the next page that comes up, find the big green box that 
says "Download" and click on that. That will bring up a page with 
a list of installers, each with a name that indicates what Python 
release the module goes with. If you have the 2.4 release, for 
instance, click on pywin32-210.win32-py2.4.exe to download the 
matching pywin32 installer.

4) When you have downloaded the installer, click on it in your 
Windows Explorer. This will execute the installer, and the entire 
pywin32 package will be installed, including win32com.

Try those steps, then try importing win32com again. 

-- 
rzed



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


Re: win32com.client

2007-01-31 Thread rzed
"vithi" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Hi
> Any one tell me where I can get (or download) python modules
> win32com or win32com.client because I have to use "Dispatch" 
> thanks 
> 

What distribution are you using? If you are using Windows and have 
downloaded the Python.org one, then, as Gary has told you:
"You want the "python for windows" extension, available from   
http://sourceforge.net/projects/pywin32/";

I think the ActiveState distro includes it as part of its package. 

I don't know if any of this applies if you are using Linux, VMS, etc.

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


Re: Are there sprintf in Python???

2007-01-22 Thread rzed
"questions?" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Are there any sprintf in Python?
> I know you can print to files(or redefine sys.stout) and later
> open the file content.
> 
> Are there similar function to sprintf in C?

Something like this?

x = 9
vbl = "One digit: %d, four digits: %04d" % (x,x)
print vbl
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT Annoying Habits (Was: when format strings attack)

2007-01-20 Thread rzed
Dane Jensen <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> On Friday 19 January 2007 22:51, Hendrik van Rooyen wrote:
>> "Steven D'Aprano" <[EMAIL PROTECTED]> wrote:
>> > Or perhaps I should say:
>> >
>> > .snoitnevnoc
>> > hsilgnE tpada )ylbissop revenehw( dluohs ew os dna ,naitraM
>> > ton ,puorgswen egaugnal hsilgnE na no er'ew ,segaugnal hcus
>> > era ereht fi neve tuB
>>
>> First I thought it was Welsh or Cornish or something.
>>
>> Then it was like being in my first year of school again-
>> reading letter by letter.  Never realised how difficult it is.
>>
>> I suppose it will improve with practice.
> 
> Not to steer this topic even futher off topic, but this is
> something that's been on my mind lately...
> 
> The biggest problem with it that the letters were forwards and
> not also backwards (and the parens). But then, it's my
> understanding that as a left-handed person, reading and writing
> backwards is far easier for me than for the majority that is
> right-handed. Have any other lefties found that the case? 

How would anybody know? As a left-hander, I have found it easy 
enough to read backwards, but then, being left-handed forces a 
certain habit of adaptability in any case. Maybe that makes it 
easier to read backward, but that is not a task I'm often called 
on to do. It takes practice regardless.

This subthread reminds me of my *highly secure* plaintext 
encryption system that would render the sentence



as 



I think it looks vaguely Esperantonic (Esperantoid? Esperantic?), 
if anything. 

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


Re: **argv can't work

2007-01-19 Thread rzed
"Jm lists" <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

> hello members,
> 
> See my script piece below:
> 
> def testB(shift,**argv):
> print "first argument is %s" %shift
> print "all other arguments are:",argv
> 
> testB('mails','Jen','[EMAIL PROTECTED]','Joe','[EMAIL PROTECTED]')
> 
> It can't work at all.please help tell me the reasons.thanks.
> 

You have too many asterisks before argv. Use just one, like this:
def testB(shift,*argv):
print "first argument is %s" %shift
print "all other arguments are:",argv

testB('mails','Jen','[EMAIL PROTECTED]','Joe','[EMAIL PROTECTED]')

Two asterisks signifies keyword arguments, like this:

def f(**c):
for k,v in c.items():
 print k,v

f(a=1,b=2)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: where is python on linux?

2007-01-07 Thread rzed
Bruno Desthuilliers <[EMAIL PROTECTED]> wrote 
in news:[EMAIL PROTECTED]:

> Frank Potter a écrit :
>> I installed fedora core 6 and it has python installed.
>> But the question is, where is the executable python file?
>> I can't find it so I come here for help.
> 
> man which
> 
> 

mmm... sloppy joes 

-- 
rzed

"A sandwich is a sandwich, but a Manwich is a meal."
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: still struggling, howto use a list-element as a name ?

2007-01-06 Thread rzed
Bruno Desthuilliers <[EMAIL PROTECTED]> wrote 
in news:[EMAIL PROTECTED]:

> rzed a écrit :
> (snip)
>> for k in self.pin.keys():
>> self.__dict__[self.pin[k]['Name']] = self.pin[k]
> 
> for pin self.pin.values():
>self.__dict__[pin['name']] = pin
> 

D'oh! Of course! Thank you.

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

Re: still struggling, howto use a list-element as a name ?

2007-01-06 Thread rzed
Stef Mientki <[EMAIL PROTECTED]> wrote in news:182cf
[EMAIL PROTECTED]:

>>> class Power_Supply(device):
>>>  pinlist = {
>>>  0: ('GND', _DIG_OUT, _par2),
>>>  1: ('VCC', _DIG_OUT, _par33)
>>>  }
>> 
>> I may be confused about what you're after, but wouldn't 
something 
>> like this work? (I don't know what a _par2 object is; I've 
named 
>> it something here.)
> _par2, is just (a reference to) a constant
>> 
>> class Power_Supply(device):
>> def __init__(self):
>> self.pin = {
>> 0:dict(Name='GND',Value=_DIG_OUT,something=_par2),
>> 1:dict(Name='VCC',Value=_DIG_OUT,something=_par33),
>> }
> Why so complex, I need 10 or more parameters (or empty),
> and then this becomes completely unreadable.
> As this is part of the "user interface",
> (I want that completely unknown with Python people,
> write these lines),
> I think my "pinlist" is much easier.
> 

Whatever works for you. In your original example, you first 
created "pinlist" (which is actually a Python dict), and then used 
it to place values in an unspecified type named "pin" (which I 
took to be another dict). I just combined the two steps.

You talk about the "pinlist" being easier ... I'm not sure what 
you mean. Easier to create? Maybe. But if you are then going to 
assign the values to names, then it doesn't strike me as easier to 
go through the two-step process. But as I said, I may be confused 
about what you are really trying to do.

> 
>> for k in self.pin.keys():
>> self.__dict__[self.pin[k]['Name']] = self.pin[k]
> thanks "rzed" ?,
> that is exactly what I was looking for:
>self.__dict__[self.pinlist[k][0]] = self.pin[k]

I'm glad it helped.

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


Re: still struggling, howto use a list-element as a name ?

2007-01-06 Thread rzed
Stef Mientki <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> In the example below, "pin" is an object with a number of
> properties. Now I want
> 1- an easy way to create objects that contains a number of these
> "pin" 2- an multiple way to access these "pin", i.e.
>  device.pin[some_index]
>  device.some_logical_name
> ad 1:
> a dictionary (as "pinlist" in the example) seems a very
> convenient 
>  way (from a viewpoint of the device creator).
> As you can see in the "__init__" section this dictionary can
> easily be transported to the pin-objects.
> 
> ad 2:
> THAT's the problem: how do automate these lines "self.GND =
> self.pin[0]" 
> 
> I'm also in for other solutions.
> 
> thanks,
> Stef
> 
> 
> class Power_Supply(device):
>  pinlist = {
>  0: ('GND', _DIG_OUT, _par2),
>  1: ('VCC', _DIG_OUT, _par33)
>  }
> 
>  def __init__(self):
>  # store pin-names and pin-parameters in pins
>  for k in self.pinlist.keys():
>self.pin[k].Name = self.pinlist[k][0]
>self.pin[k].Value = self.pinlist[k][2]
> 
>  # for some pins, we also want to be able to use logical
>  names # HOW TO USE SOMETHING like
>  # "self.pinlist[0] = self.pin[0]"
>  # INSTEAD OF
>  self.GND = self.pin[0]
>  self.VCC = self.pin[1]
> 
> # create a Power_Supply instance and
> # test if pins can be referenced in
> Power = Power_Supply()
> netlist1 = ( Power.VCC, Power.pin[1], Power.GND, Power.pin[0] )

I may be confused about what you're after, but wouldn't something 
like this work? (I don't know what a _par2 object is; I've named 
it something here.)

class Power_Supply(device):
def __init__(self):
self.pin = {
0:dict(Name='GND',Value=_DIG_OUT,something=_par2),
1:dict(Name='VCC',Value=_DIG_OUT,something=_par33),
}
for k in self.pin.keys():
self.__dict__[self.pin[k]['Name']] = self.pin[k]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Just Getting Started with Python on MS XP Pro

2007-01-06 Thread rzed
[EMAIL PROTECTED] wrote in
news:[EMAIL PROTECTED]: 

> Wise choice + welcome to the club.

Seconded.

> The only real XP drawback is that Python is not bundled on
> Windows, while it is included with OS X and most (all?) Linux
> distros. 
> 

My computer does, in fact, include a Python 2.2.1 installation, 
which the manufacturer uses internally.

> 2.  use any ol' text editor that _you_ are familiar with, save
> to file, and python  under DOS.  later on you can always
> pick an editor. i prefer eclipse + pydev, yes, even on windows.
> 
> personally, i find pythonwin _great_ to test out code
> interactively, mediocre to write lots of code with and
> occasionally handy to debug code in.
> 
> if you hate typing python  under DOS, then I guess you
> will have to run programs from pythonwin.
> 

Not so, but it takes a little setup. If I want to run a Python 
program named, say, "fixthis.py", I can invoke it by typing 
"fixthis.py" at the command-line prompt (if I'm running cmd.exe), 
or by clicking the icon in Windows Explorer. To make the command-
line option work, I have to have file associations set so that .py 
files open with python (and .pyw files open with pythonw, for that 
matter). I *think* this is done at install time, though I may have 
done that separately.

There is also an environment variable called "pathext", which is 
just a list of extensions the system recognizes as being 
executable in some way. if you add .py and .pyw to that list, then 
all you have to type at the command line is "fixthis" to get that 
Python program to run.

I note that I have had my Python root and Python/Scripts directory 
on my path at times. There may be some packages that require these 
things, but what I talked about in the previous two paragraphs 
doesn't require pythonpath to be set specially.

(Fiddling around) Ah! If you want to invoke the interactive python 
shell, you will probably want to add the root location to your 
path, so you can type
> python
... to invoke it, rather than
> c:\python25\python
... and something similar may be true for the Scripts 
subdirectory.

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


Re: function without brackets ?

2007-01-03 Thread rzed
Stef Mientki <[EMAIL PROTECTED]> wrote in news:57668
[EMAIL PROTECTED]:

> If I call a parameterless function without brackets at the end,
> the function is not performed, but ...
> I don't get an error message ???
> 
> Is this normal  behavior ?
> 

Yes, it's normal, but you did not in fact call the function, if you 
were using Python. Functions are objects that, for example, can be 
passed to other functions. The way to refer to the functions 
themselves is to omit the arguments and parentheses. So by simply 
stating the name of a function, that's all you've done. 

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


Re: File write() problem

2006-12-27 Thread rzed
[EMAIL PROTECTED] wrote in
news:[EMAIL PROTECTED]: 

> Marc 'BlackJack' Rintsch wrote:
> 
>> > configfile = file('config.txt', 'w')
>> > serverPassword = configfile.readline()
> 
> Hrm. When I run the code that I posted I don't seem to get those
> errors.
> 
>> Please post the exact code you have trouble with.  Don't retype
>> it -- copy and paste it.
> 
> from getpass import getpass
> 
> configfile = file('config.txt', 'w')
> serverPassword = configfile.readline()
> if serverPassword == '':
>print "Server warning: No password has been set!"
>pwd1 = getpass("New Password: ")
>pwd2 = getpass("Confirm Password: ")
>while pwd1 != pwd2:
>print "Passwords did not match."
>pwd1 = getpass("New Password: ")
>pwd2 = getpass("Confirm Password: ")
>print "Password set. Storing to admin/config..."
>configfile.write(pwd2)
>serverPassword = configfile.readline()
>configfile.close()
> 
> Again I tested the code before I posted and I get no errors,
> just not the result I am looking for in the text file. Thanks
> for taking the time to look at it.
> 

As Marc points out, you are opening the file in write mode and 
then reading from it. Did you try printing out what gets placed 
into serverPassword the first time? It may not be what you expect, 
for starters. But now the file pointer is at the end of the file, 
and that's where you write the input password. Amazingly, Python 
lets you do this, but even if you could read back those characters 
you just wrote by doing a readline() (which might be getting data 
from the ether by now), the password wouldn't be written over the 
original, but instead would be on the next line.

If your intent is to update a flat file, you can try using seeks 
and rewinds and such to position the file pointer appropriately, 
but you'll still be in misery as soon as someone replaces the 
password "G811ploo" with "ALongerPassword". Flat files aren't 
databases. You're better off reading the entire file (opened in 
read mode) into memory and closing it, then re-opening it in write 
mode and writing out the entire thing with the changed password, 
replacing the original file.

-- 
rzed
... for some value of better off...

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


Re: Formatting a string to be a columned block of text

2006-12-26 Thread rzed
"Dave Borne" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Thanks, Paul. I didn't know about textwrap, that's neat.
> 
> Leon,
> so in my example change
>> data1= [testdata[x:x+colwidth] for x in
>> range(0,len(testdata),colwidth)] 
> to
>> data1 = textwrap.wrap(testdata,colwidth)
>> data1 = [x.ljust(colwidth) for x in data1]
> 
> oh and I made a mistake that double spaces it. the "print '\n'"
> line needs to be either
> print ''
> or
> print '\n',
> (with a comma)
> 

The solutions so far serve up text that is split within the 
confines of the column width, but leave a "ragged right" margin, 
where the line lengths appear to differ. I had the impression that 
the OP wanted right-and-left justified text, such as would 
typically be found in a newspaper column. Here's a shot at doing 
that for fixed-width fonts. To use it, first split your lines as 
others have suggested, then print aline(line,colwid) for each line 
in your data. 

# aline - align text to fit in specified width
# This module arbitrarily chooses to operate only on long-enough 
# lines, where "long-enough" is defined as 60% of the specified 
# width in this case. 
#
def aline(line, wid):
line = line.strip()
lnlen = len(line)
if wid > lnlen > wid*0.6:
ls = line.split()
diff = wid - lnlen
#nspaces = len(ls)-1
eix = 1
bix = 1
while diff > 0: # and nspaces > 0:
if len(ls[bix]) == 0 or ls[bix].find(' ') >= 0:
ls[bix] += ' '
else:
ls.insert(bix,'')
diff -= 1
bix += 2
if bix >= 1+len(ls)/2: bix = 1

if diff > 0:
if len(ls[-eix]) == 0 or ls[-eix].find(' ') >= 0:
ls[-eix] += ' '
else:
ls.insert(-eix,'')
diff -= 1
eix += 2
if eix >= 1+len(ls)/2: eix = 1
line = ' '.join(ls)
return line

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


Re: what is wrong with my code?

2006-12-20 Thread rzed
Pyenos <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

> thanks for your point. so because i have said class blah: i must
> explicitly say self for every instantiation of object?
> 

No, for every method within the class.

Given:

class Blah(object):
def method1(self,arg1):
self.x = arg1


b = Blah()  # b is an instance of class Blah

b.method1(32)   # when you invoke it, just pass arg1

print b.x   # prints 32



The use of 'self' is just a convention, but a *very* common one, 
and one you should follow if you expect other Python programmers 
to read your code. This is legal, and has the same effect as the 
above class:

class Blah2(object):
def method1(spugsl,arg1):
spugsl.x = arg1

Spugsl (or self) is just the way to refer to the instance within 
the code.

In your code, each method wound up with a different name, and none 
of the names would have been associated with what you would have 
expected. So for example, in 

def removeEntry(pid_to_remove, task_to_remove):

... your equivalent to 'self' would be pid_to_remove, and the pid 
you passed in would have been associated with task_to_remove.

-- 
rzed



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


Class and instance question

2006-12-17 Thread rzed
I'm confused (not for the first time). 

I create these classes:

class T(object):
def __new__(self):
self.a = 1

class X(T):
def __init__(self):
self.a = 4

class Y:
def __init__(self):
self.a = 4

class Z(object):
def __init__(self):
self.a = 4


... and these instances:

t = T()
x = X()
y = Y()
z = Z()

and I want to examine the 'a' attributes.

>>> print T.a
1
>>> print y.a
4
>>> print z.a
4

So far, it's as I expect, but:

>>> print x.a
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'NoneType' object has no attribute 'a'

>>> print t.a
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'NoneType' object has no attribute 'a'

So what the heck is 'T'? It seems that I can't instantiate it or 
derive from it, so I guess it isn't a proper class. But it's 
something; it has an attribute. What is it? How would it be used 
(or, I guess, how should the __new__() method be used)? Any hints?

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


Re: aggdraw for 2.5 on WinXP?

2006-12-15 Thread rzed
Stéphane Muller <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> rzed a écrit :
>> Has anyone generated an aggdraw installer or aggdraw.pyd for
>> Python 2.5 (WinXP)? If so, could it be made available for those
>> of us who don't have a working compiler?
>> 
> Hello,
> 
> You can try
> 
> http://c.python.free.fr/aggdraw-1.2a3-20060212.win32-py2.5.exe
> 
> without any express or implied warranty.
> 

Thank you, Stephane. I have an aggdraw.pyd file now, but 
unfortunately, I am unable to produce images using the 2.5 
version. I also need to write text to some of the images and the 
font factory and when I try to create a font, I get: IOError: 
cannot load font (no text renderer) with the same code that works 
with 2.4. When I try to produce files, they don't load in my 
viewer. I guess I have to look a little deeper into the issue to 
find out what's really going on. I do appreciate your taking the 
trouble to produce the installer, though. 

-- 
rzed

 

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

aggdraw for 2.5 on WinXP?

2006-12-14 Thread rzed
Has anyone generated an aggdraw installer or aggdraw.pyd for Python 
2.5 (WinXP)? If so, could it be made available for those of us who 
don't have a working compiler?

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


Re: PythonTidy

2006-12-05 Thread rzed
Chuck Rhode <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> That went well.  PythonTidy has been looked at at least 10**2
> times, and I have received a couple of complaints, which I hope
> I have addressed satisfactorily -- plenty good enough for a beta
> test.  The basic concept stands.
> 
> PythonTidy.py cleans up, regularizes, and reformats the text of
> Python scripts:
> 
>   http://www.LacusVeris.com/PythonTidy/PythonTidy.python
> 
> What next?  Is it appropriately submitted to the Cheese Shop?
> 

I ran PythonTidy on a wxPython sample, and found that wx.CONSTANTS 
were being translated to wx.Constants, which won't do at all.

In general, there is very little case manipulation that should be 
done in a case-sensitive language; I suppose this is controllable 
by one or more of the options, but it wasn't clear on casual 
observation what would do the trick. 

The idea of PythonTidy is not bad, but there should be a minimal 
option that essentially reindents and nothing more. Adding other 
style preferences should (in my opinion) be something like 
checklist items. For example, I don't necessarily need a shebang 
or coding line for my purposes, but without going into the code 
and commenting out lines, I can't readily suppress them. As it 
stands now, I can't trust PythonTidy to do the right thing on 
unfamiliar code, and I can't readily try out various options by 
simply activating or deactivating them; if I could, it would be 
much more useful to me.

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


Re: A question about list

2006-10-17 Thread rzed
[EMAIL PROTECTED] wrote in news:1161102973.920895.141500
@i42g2000cwa.googlegroups.com:

> Hello:
> Variable 'a' has the next values:
> [[1,1],[2,2]]
> and I want to take a to b as:
> [[1,1,'='],[2,2,'=']]
> How can I do this with only one line of instruction?
> Thanks!!
> 

b = [[x,y,'='] for (x,y) in a]

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


Re: does anybody earn a living programming in python?

2006-09-28 Thread rzed
"Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

[...]
> Oh dont be so pedantic - countless - without count - probably
> just means that nobody has bothered to count them...

Without being particularly pedantic: no, it doesn't. It means "too 
many to count". Though I would have taken Anthony's usage ("there's 
countless other people I know...") less than literally.

-- 
rzed

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


Re: New Python.org website ?

2006-01-11 Thread rzed
Steve Holden <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Bugs wrote:
>> Aahz wrote:
>> 
>>>Dunno about "in time for the new year", but there is a new
>>>design that is supposedly in final stages of getting
>>>implemented.  What's your hurry? 
>> 
> [...]
> http://beta.python.org
 
So what's the character encoding? I haven't found (WinXP Firefox) 
that displays that city in Sweden without a paragraph symbol or 
worse. 

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


Re: Python 2.4 - Help does not work in Windows

2006-01-05 Thread rzed
[EMAIL PROTECTED] wrote in
news:[EMAIL PROTECTED]: 

> I've just upgraded from Python 2.3.3 to Python 2.4.2, and,
> although the new version of Python seems to be running
> correctly, I can't seem access the help from the interpreter.
> 
> On Python 2.3.3
> ---
> Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more
> information. 
>>>> import time
>>>> time.ctime()
> 'Wed Jan 04 12:59:13 2006'
>>>> help(time)
> Help on built-in module time:
> 
> NAME
> time - This module provides various functions to manipulate
> time 
> values.
> 
> ... etc ...
> 
> On Python 2.4.2
> ---
> Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more
> information. 
>>>> import time
>>>> time.ctime()
> 'Wed Jan 04 13:01:22 2006'
>>>> help(time)
> cannot import name warn
> 
> I get this warning for all modules which I've tried. I guess
> this is an installation problem, and have tried uninstalling and
> re-installing but that gives me the same results.
> 
> Could anyone give me some pointers on where I might look to
> debug this problem? In case it's any help, I'm running Windows
> XP SP2, and have installed both Python2.3 and Python 2.4 on the
> same system. Could this be causing some conflict?
> 
> Any help would be greatly appreciated!
> 

I've been running 2.4.x for some time on a Win2K machine, with no 
problems. Just recently I got an XP system, and after installation 
of numerous things, I had help disappear(!). That is, I am *fairly* 
certain that at one point it worked in Python and later did not, on 
that same system. It is possible that it never did on XP, though. 

Incidentally, this manifested itself both in Python and in the 
system command line (cmd.exe), for some reason. I expect there was 
a clash with some other software I installed. 

At any rate, I re-installed Python over the top of the existing 
installation, and *both* Python help and the command-line help 
reappeared. I don't know what to make of that. 

The XP system does have a Python 2.2.3 version that came pre-
installed, though I've not used it directly. (checking) It's help 
seems to work now, but then so does my 2.4.2 help, now.

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


About zipfile on WinXP

2006-01-02 Thread rzed
I create a zip file on my WinXP system, using this function:


import zipfile
import os
import os.path

def zipdir(dirname, zfname):
zf = zipfile.ZipFile(zfname, 'w', zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(dirname):
for f in files:
fullname = os.path.join(root, f)
zf.write(fullname)
zf.close()


The file is created, and, again using zipfile, I can read it and 
extract from it and so on. 

However, WinXP has a "feature" (if that's what it is): if you click 
on a zip file in explorer, an explorer window opens that shows the 
contents of the zip file. If I use WinZip or UltimateZip to create 
the files, this works more-or-less okay, but when I click on the 
zip file Python creates, no content shows at all (just a blank 
explorer window). If I explicitly use one of the other zip-handling 
packages, I can view the python-created file's contents.

Has anyone else observed this? If not, is there something in the 
code that I should change to permit XP to view the contents? 

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


Build Python using Mars compiler?

2006-01-01 Thread rzed
Has anyone tried to compile Python (on Windows) using the Digital 
Mars compiler? If so, can you give some hints how you did it? 

Or ... can anyone suggest an approach to compiling from the ground up 
using a compiler that isn't mentioned in the thicket of #ifdefs? 
Where to start? What to look out for?
-- 
rzed
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows and python execution

2005-12-26 Thread rzed
Mark Carter <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Bengt Richter wrote:
> 
>>>>And there is a PATHEXT environment variable, 
>>>
>>>Aha. You'bve provided a significant clue.
>>>
>>>What you need to do is include the following line in
>>>autoexec.bat: set .py=c:\python24\python.exe
>>>
>>>This will achieve the desired result. I'm suprised more people
>>>don't use it. 
>> 
>> I wasn't aware of that syntax for set. What OS/platform/shell
>> is that from? 
> 
> Windows XP, bog-standard default shell. UNIXers have it easy
> because they can use the normal "shebang".
> 
>> How did you go from the PATHEXT "clue" to the set command you
>> specify 
> 
> I can't remember. It was a bit of luck, I think. I happened
> upon: http://www.jpsoft.com/help/index.htm?exeext.htm
> probably as a result of Googling for PATHEXT.
> 
>> and decide
>> not to set pathext, e.g., by something like
>> set PATHEXT=%PATHEXT%;.py
>> Does your set do the pathext and assoc and ftype all in one
>> swell foop? 
> 
> Actually, I haven't figured out what PATHEXT is actually
> supposed to "do". It seemed to me that Windows couldn't possibly
> know that a py file should be started by python.exe, whereas my
>  set .py= ...
> would.
> 
> I had installed python 2.4 in the standard way, so py files were
> already associated with python when you double-clicked them from
> Explorer. Using my set meant that if I wanted to use py files
> from the command line, I could just type out the script name
> (you have to be in the right directory, of course), and it
> works. Here's a snippit from my autoexec.bat files:
> set PATH=C:\python24;%PATH%
> set .py=c:\python24\python.exe
> 

I should have asked which Windows version you had. My bad. On Win2k 
or XP, adding .py (for instance) to the PATHEXT variable means that 
you can execute "myNeatProgram.py" with this command-line:
prompt>myNeatProgram

Since .py appears in the PATHEXT variable, the system knows that 
.py files are executable, so it's not necessary even to specify 
them. What must happen, I suppose, is that the system looks for 
myNeatProgram.bat, myNeatProgram.com, myNeatProgram.exe, etc., 
until it hits upon myNeatProgram.py and proceeds to run it. So if 
you have a myNeatProgram.bat that appears earlier in your path than 
myNeatProgram.py does, the bat file is what gets run.

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


Re: Windows and python execution

2005-12-26 Thread rzed
Mark Carter <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> What I would like to do it type something like
> > myscript.py
> instead of
> > python myscript.py
> on a Windows console. I know its possible because Ruby scripts
> manage to do this - I just don't know the registry settings that
> need to be tweaked to enable it. Any ideas (I'd prefer to know
> the registry settings rather than a graphical way to accomplish
> the goal)? 

As another poster points out, be sure that your Python is on your 
path. 

And there is a PATHEXT environment variable, which contains 
extensions that signal that the program is executable. Add .PY and 
.PYW to this list and you will be good to go.

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


Re: Parsing text

2005-12-20 Thread rzed
"sicvic" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Not homework...not even in school (do any universities even
> teach classes using python?). Just not a programmer. Anyways I
> should probably be more clear about what I'm trying to do.
> 
> Since I cant show the actual output file lets say I had an
> output file that looked like this:
> 
> a b Person: Jimmy
> Current Location: Denver
> Next Location: Chicago
> --
> a b Person: Sarah
> Current Location: San Diego
> Next Location: Miami
> Next Location: New York
> --
> 
> Now I want to put (and all recurrences of "Person: Jimmy")
> 
> Person: Jimmy
> Current Location: Denver
> Next Location: Chicago
> 
> in a file called jimmy.txt
> 
> and the same for Sarah in sarah.txt
> 
> The code I currently have looks something like this:
> 
> import re
> import sys
> 
> person_jimmy = open('jimmy.txt', 'w') #creates jimmy.txt
> person_sarah = open('sarah.txt', 'w') #creates sarah.txt
> 
> f = open(sys.argv[1]) #opens output file
> #loop that goes through all lines and parses specified text
> for line in f.readlines():
> if  re.search(r'Person: Jimmy', line):
>  person_jimmy.write(line)
> elif re.search(r'Person: Sarah', line):
>  person_sarah.write(line)
> 
> #closes all files
> 
> person_jimmy.close()
> person_sarah.close()
> f.close()
> 
> However this only would produces output files that look like
> this: 
> 
> jimmy.txt:
> 
> a b Person: Jimmy
> 
> sarah.txt:
> 
> a b Person: Sarah
> 
> My question is what else do I need to add (such as an embedded
> loop where the if statements are?) so the files look like this
> 
> a b Person: Jimmy
> Current Location: Denver
> Next Location: Chicago
> 
> and
> 
> a b Person: Sarah
> Current Location: San Diego
> Next Location: Miami
> Next Location: New York
> 
> 
> Basically I need to add statements that after finding that line
> copy all the lines following it and stopping when it sees
> '--'
> 
> Any help is greatly appreciated.
> 

Something like this, maybe?

"""
This iterates through a file, with subloops to handle the 
special cases. I'm assuming that Jimmy and Sarah are not the
only people of interest. I'm also assuming (for no very good
reason) that you do want the separator lines, but do not want 
the "Person:" lines in the output file. It is easy enough to 
adjust those assumptions to taste.

Each "Person:" line will cause a file to be opened (if it is 
not already open, and will write the subsequent lines to it 
until the separator is found. Be aware that all files remain 
open unitl the loop at the end closes them all.
"""

outfs = {}
f = open('shouldBeDatabase.txt')
for line in f:
if line.find('Person:') >= 0:
ofkey = line[line.find('Person:')+7:].strip()
if not ofkey in outfs:
outfs[ofkey] = open('%s.txt' % ofkey, 'w')
outf = outfs[ofkey]
while line.find('-') < 0:
line = f.next()
outf.write('%s' % line)
f.close()
for k,v in outfs.items():
v.close()

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


Re: If - Or statements

2005-06-04 Thread rzed
Ognjen Bezanov <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Robert Kern wrote:
> 
>> Ognjen Bezanov wrote:
>>
>>> Another newbie-ish question.
>>>
>>> I want to create an if statement which will check if a
>>> particular variable matches one of the statements, and willl
>>> execute the statement if the variable matches any of the
>>> statements. 
>>>
>>> I have tried the following (the pass is just used for testing)
>>>
>>>
>>> if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg" or
>>> ext[1] == "aac" or ext[1] != "wma":
>>>print "we have a valid extension: " + ext[1] #here
>>>would go the 
>>> code for decoding the above
>>>pass
>>
>>
>> It works fine for me. Could you post the smallest complete
>> program (one that defines ext) that displays the behavior and
>> its entire output? 
>>
>> As an aside, is 'ext[1] != "wma"' correct or should it be ==?
>> As written, you could collapse the whole thing to 'if ext[1] !=
>> "wma":' but I presume it is a typo.
>>
> filelist = os.listdir('/mnt/cdrom/') #get a list of files from
> the cdrom drive
> for thefile in filelist[:]:   #for each file in the
> filelist 
> if thefile.find(".") != -1:   #if the file has an
> extenstion 
> at all
> ext = thefile.split('.') #get the file extension
> ext[1] =  ext[1].lower() #convert to lowercase
> print ext[1] #debugging, to see the variable
> before 
> passed to if statement
> 
> if ext[1] == "mp3" or ext[1] == "mp4" or ext[1]
> == "ogg" 
> or ext[1] == "aac" or ext[1] == "wma":
> print "we have a valid extension: " + ext[1]
> #here 
> would go the code for decoding the above
> pass

Though this may sidetrack the issue, another way of doing multiple 
checks like that is to make a list and check for inclusion in the 
list. Something like this:
exts = ['mp3','mp4','ogg','aac','wma']
if ext[1] not in exts:
# do whatever

or
if ext[1] in exts:
print 'we have a valid extension:',ext[1]

It's easier to add to the list than to add another explicit test, 
particularly if the tests occur in several places.
-- 
rzed
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question: Allocation vs references

2005-06-02 Thread rzed
Jan Danielsson <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Hello all,
> 
> Behold:
> 
> --
> a = [ 'Foo', 'Bar' ]
> b = [ 'Boo', 'Far' ]
> q = [ a, b ]
> 
> print q[0][0]
> print q[1][1]
> 
> a[0] = 'Snoo'
> b[1] = 'Gnuu'
> 
> print q[0][0]
> print q[1][1]
> --
> 
> This will output:
> Foo
> Far
> Snoo
> Gnuu
> 
>I assume it does so because q stores _references_ to a and b.
>How 
> would do I do if I want to copy the list? I.e. I want the output
> from the code above to be:
> 

If your original assigment to q were:
q = [ a[:], b[:] ]
... you would have copies of a and b, so that:

>>> a = [ 'Foo', 'Bar' ]
>>> b = [ 'Boo', 'Far' ]
>>> q = [ a[:], b[:] ]
>>> print q[0][0]
Foo
>>> print q[1][1]
Far
>>>
>>> a[0] = 'Snoo'
>>> b[1] = 'Gnuu'
>>>
>>> print q[0][0]
Foo
>>> print q[1][1]
Far

> Foo
> Far
> Foo
> Far
> 
> ..even if a[0] = 'Snoo' and b[1] = 'Gnuu' remain where they are.
> 
>Or, better yet, how do I store a and b in q, and then tell
>Python 
> that I want a and b to point to new lists, without touching the
> contents in q?

That's easier:
>>> a = [ 'Foo', 'Bar' ]
>>> b = [ 'Boo', 'Far' ]
>>> q = [a,b]
>>> a = ['Splee','Hoongk']
>>> b = ['Blik','Poit']
>>> print q[0][0]
Foo
>>> print q[1][1]
Far

You've stuck the 'a' and 'b' labels on new objects this way. The 
original objects would vanish except that there is still a reference 
to them through the 'q' list.

> 
> C equivalent of what I want to do:
> ---
> a = calloc(n, size);
> prepare(a)
> 
> q[0] = a;
> 
> a = calloc(n, size);  // new list; 'q' is unaffected if I change
> 'a' ---



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


Re: anygui,anydb, any opinions?

2005-06-01 Thread rzed
"Thomas Bartkus" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> "rzed" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> 
>> So what do you think? What's wrong with the picture? Why isn't
>> there a greater priority to work in this direction?
> 
>   > What's wrong with the picture?
> 
> Just one teeny little item.
> 
> The Python world lacks the phenomenally successful development
> models enjoyed by the now ancient Turbo Pascal, Delphi and
>  Visual Basic. 
> AND
> If the likes of Visual Basic can have it, then it becomes
> really, *really* hard to convince the world that Python is a
> serious, professional system. 
> 
> At some point, one has to break out of theory and produce!
> Or challenge the theory with some hard questions.
> 

I'm not thinking only of a Drag & Drop graphical development 
interface (and in fact there are several available now, all of 
which work with some degree of similarity to VB). It might be nice 
to have, but I've used a lot of systems that could crank out 
tolerable windows with a relatively small amount of text entry. 
Those who have used Cognos' Powerhouse, for instance, or Magic, or 
even dBase (maybe that's a stretch) can testify to that, I think.

But there is a common need for production of systems where data-
entry and data views are required. Typically, the back end is a 
database, though it need not be. It's not that hard to build such a 
system using any one of the packages, particularly once you acquire 
expertise with that package. 

But should you want to switch to another package, you find that a 
*lot* has to change in your applications, no matter how hard you've 
tried to separate the presentation from the logic, just because the 
requirements of the various systems differ so much. It might be 
that you have to reorder parameter lists, or subtract parameters, 
or insert some. Almost never can you simply use a different import 
statement alone to change the underlying windows handler. If you 
need to add new parameters, almost never can you simply append them 
to an existing parameter list and expect the thing to work. 

And if you do change to the new system, your code can no longer 
work using the old system. A lot of this is just because of the way 
interfaces are specified; for some call on system A you need, let's 
say: (a)a label, (b)a size (which must be a tuple, not a list), (c)
a boolean value. Now you switch to system B, which does not name 
the equivalent call the same, nor does it pass in the same 
parameters, or not in the same sequence. Multiply this by all the 
api calls you have, and you may as well start over with each 
package as try to make it all work.

It seems to me that Python (the language, not the package) is 
intended in part to make tasks like that easier. It would be better 
if the call for a given function were named the same (in your 
application code), and if you could simply append some new 
parameters to make the new system function (knowing that its 
interface would simply ignore the old parameters it did not 
understand), well, that's not too hard, and it doesn't break the 
old system. So you add what you need to (if you need to add 
anything), and now you have a system that runs on two packages. All 
you have to do is to import the one you have, or want to use. 

It means the package writer has to create an API bridge, one that 
maps the underlying package's api to the Python standard api. The 
application writer doesn't or shouldn't have to worry about that 
mapping. And it probably means that dictionaries (or something 
similar) are used to pass most parameters. 

This sounds chaotic, as though interfaces would suddenly be 
impossible to document, but it need not be so. If a package has a 
feature that cannot be mapped reasonably to the Python api, then 
add to the Python api, or (as part of the Python api) allow a 
system pass-through the package's api can interpret. If the package 
doesn't get the information it needs, it will complain, just as it 
does now. Its requirements will be documented just as they are now. 

It's not that all applications would run on all systems without 
change, but that essentially all *basic* applications would run on 
any system that supported the same basic operations without change. 
There are many widgets, and as windowing packages become slicker, 
there are more options; eventually, as the options become universal 
(or at least common) they would be added to the Python api.

Whether or not a D&D GDI would make this better would still be up 
to the individual programmer, I'd think. It would be a heck of a 
lot easier to *write* a GUI if you weren't overly concerned with 
the underlying graphics package. 

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


anygui,anydb, any opinions?

2005-05-31 Thread rzed
Periodically, we see questions about which gui package is best, or 
which database package to use. These questions typically trigger 
some exchanges of opinion, though of course this no one best 
answer, and eventually things quiet down until the next round.

But it seems to me that what seldom gets asked is: why is it 
Python's concern which package to use for those purposes? It seems 
to me that a proper approach from the viewpoint of the language 
itself is to provide an interface, and for the package developers 
to provide an implementation of that interface. A Python program 
would thus address its api only, leaving it up to the package to 
interpret that properly. In the ideal world, this would mean that 
any Python program could swap the gui package (or the db package) 
without changing the logic of the program. Python-the-language 
(rather than Python-the-package) would theoretically be a more 
compact download, and the hooked-in parts could be installed 
separately.

Anygui and anydb have been attempts to reach the ideal interface 
(and there are others, I think), but each has its problems and 
neither is supported or developed as fully as the idealized 
interface would require. I don't see much evidence that the various 
packages are designed to conform to those designs (and I don't 
contend that they should be required to until and unless the 
generic interfaces are in a well-developed state). But the result 
of all this is that there continues to be confusion to newbies and 
even veterans who are new to a given area or platform. Shouldn't it 
be a priority to eliminate the source of that confusion?

Now, on the grounds that practicality beats purity, it's certainly 
reasonable to argue that the current system works better. If we 
could just jump into a state where there was a perfectly-
functioning anydb and anygui, then we'd already have been there, 
but we can't and so we won't try to go in that direction at all. 
Python-the-package marches on; it can't wait for some ideal to 
coalesce before it advances. It's hard to argue too strongly 
against that view.

Then, too, it's hard to see how an anygui or (more especially, I 
think) an anydb could possibly work in the real world. The various 
approaches to windowing and databases are too different for a 
single interface to encompass them all. Some capabilities would be 
unforeseen or ignored in any such interface. That argument carries 
a lot of force. Certainly it is true that adding parameters to a 
function call to accommodate some new feature gets real old real 
soon. But while it is a strong practical argument, it is not one 
that truly wins in the long run, I think. It is an argument in 
favor of changing the way arguments are passed, so that it becomes 
possible to handle the various pieces of information the lower-
level package needs. The interface should be agnostic as much as 
possible. The package should be able to get the information it 
needs from what is passed by the api. Both of these things must be 
true.

Back when I was programming in DEC C, I saw how their 
implementation of functions like printf departed from the C 
standard by adding optional keyword parameters. Using those 
parameters, DEC's more-sophisticated filesystem could be used 
productively without going deeply into the filesystem's api. 

Of course, a program written that way wouldn't work if transferred 
unchanged to another system, but it *could* have worked if the 
other system could also either handle the keywords (or some of 
them) or ignore them. The results may not have been exactly as 
desired, but there would have been results. Similarly, an elaborate 
call that allows access to a sophisticated gui should also produce 
results if the gui is simpler. Supposing that a given parameter 
required by the second system has not been included in the first 
place, it should be possible to add that parameter without 
affecting the first system one bit. The first one would still not 
be looking for the parameter, while the second would now find it.

That's all I'm talking about here. To be able to write a Python 
application that can ultimately be displayed using wxWidgets or Qt 
or Tkinter or Curses. Then, without having to do more than to 
change which interface package is imported, to expect to see the 
result displayed. To have it just happen, and to have expectations 
when using Python that it *will* just happen that way.

So what do you think? What's wrong with the picture? Why isn't 
there a greater priority to work in this direction?

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


Re: PIL and line drawing

2005-05-24 Thread rzed
"Fredrik Lundh" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> "rzed" <[EMAIL PROTECTED]> wrote:
> 
>> > if you have 1.1.5, you can use the width option to control
>> > the line width. see:
>>
>> I'm glad to see that addition. I was surprised to see that
>> 'width' is actually doubled in the resulting line, though. I
>> suppose the code adds and subtracts the specified width from
>> the specified coordinate point(?).
> 
> hmm.  that sure sounds a lot like a bug I though I had fixed.
> 
Ah, I see that I was using   VERSION = "1.1.5b1" which I have now
upgraded to 1.1.5. Retesting ... nope, same thing. Specifying a
width of 10, I get a line of width 20. ImageDraw shows: 

# $Id: ImageDraw.py 2134 2004-10-06 08:55:20Z fredrik $

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


Re: PIL and line drawing

2005-05-20 Thread rzed
"Fredrik Lundh" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Leonard J. Reder wrote:
> 
>> I am using PIL to annotate some images with lines.  I could not
>> find anyway to make the line that is drawn from the ImageDraw
>> object thicker.  Does anyone have a suggestion or solution for
>> solving this without to much hacking?
> 
> if you have 1.1.5, you can use the width option to control
> the line width. see:
> 

I'm glad to see that addition. I was surprised to see that 'width' 
is actually doubled in the resulting line, though. I suppose the 
code adds and subtracts the specified width from the specified 
coordinate point(?). I'd love to see width added to arc, circles, 
etc., though if it is, I'd much prefer that it not be centered on 
the coordinate point, but added only to the outer edge (or 
subtracted from the inner edge); it would make placement much 
easier, I'd think. 

At the moment, whenever I need to generate thick-lined circles and 
rectangles, I have to create a second image of the desired color, 
then another mask image to contain a black rectangle (say) of the 
required outer size, then within that a white rectangle of the 
inner size, then use that mask to paste the color onto the original 
image. The results are satisfactory, but the method seems clunky at 
best. Maybe there's a better way. Even if this were the exact 
method used, I'd rather see it automated in C than manually done in 
Python.

> http://effbot.org/imagingbook/imagedraw.htm
> 
>> Thanks for any replies,
> 
> tip: you may get quicker/better responses if you use the
> image-sig mailing list (if you're using a newsreader, point
> it to gmane.comp.python.image)
> 


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


Re: Setting the corner color in rotated PIL images

2005-05-10 Thread rzed
"Fredrik Lundh" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> "rzed" wrote:
> 
>> I'm using PIL to generate some images which may be rotated at
>> the user's option. When they are rotated, the original image is
>> cropped in the new image (which is fine), and the corners are
>> black (which is not, in this case). I can't find any documented
>> way to change the default fill color (if that's what it is) for
>> the corners, and PIL also doesn't seem to support a flood fill.
>> I have created a flood fill in Python, which works but which
>> markedly slows image generation.
>>
>> Can anyone suggest a better way to set the color of the
>> corners? 
> 
> if you're doing this on RGB images, the quickest way to do this
> is: 
> 
> def rotate(image, angle, color):
> bg = Image.new("RGB", image.size, color)
> im = image.convert("RGBA").rotate(angle)
> bg.paste(im, im)
> return bg
> 
> here's a more general solution:
> 
> def rotate(image, angle, color, filter=Image.NEAREST):
> if image.mode == "P" or filter == Image.NEAREST:
> matte = Image.new("1", image.size, 1) # mask
> else:
> matte = Image.new("L", image.size, 255) # true matte
> bg = Image.new(image.mode, image.size, color)
> bg.paste(
> image.rotate(angle, filter),
> matte.rotate(angle, filter)
> )
> return bg
> 
>  
> 
Fredrik:

Thank you for the reply. It just showed up on my server, and, of 
course, it works perfectly.

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


Re: Setting the corner color in rotated PIL images

2005-05-06 Thread rzed
"Anthra Norell" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> What do you mean 'is required'? I tend to think that getting
> ahead with a job is what is required. I don't sneer at
> work-arounds if they save time. 
> 
> Frederic
> 
> A somewhat craftier solution, if still pretty hackish, would be
> to go through your image pixel by pixel, look what color each
> one is (color = image.getpixel (here)) and change the ones with
> the wrong color (if color == wrong_color: putpixel (here,
> right_color)). 
>   If the color of  the corners does not occur inside your
>   picture, you 
> can go throught the entire image. Else you'd have to stop
> changing colors at the first occurrence of a pixel that does not
> have the wrong color, coming inward from each of the lateral
> edges. (Code below (untested)). 
>   If you have elements in your picture that not only have
>   the same color 
> as the corners, but also run into them, then you might have to
> refine your code further in order for the inner loop not stray
> into the image. 
> 

[Code snipped]

Yes, that is essentially similar to the slow flood-fill approach I 
used initially. I did in fact make use of your previous suggestion, 
which works but requires oversizing the image, calculating the crop 
rectangle and so on -- not overly difficult, just annoying -- and I 
also use another approach (outlined in another message) that 
involves pasting a rotated copy of the image back onto the original 
under control of a mask. It depends on what I want to see in the 
corners, essentially. And, having coded the workarounds, I get on 
with the process without worrying about it.

But ... it would be nice if I could specify a default solid color 
to replace the black in the corners, and have the rotation take 
place in one operation without resizing and recalculating and 
duplicating images and all. 

Somewhere down in the C code, the "corner" color is being set to 
black. I wouldn't think it would be terribly hard at that stage to 
set those bytes to other values instead, and exposing that color 
through PIL's interface. But I suppose it's more trouble than it's 
worth for Fredrik, or nobody else has been bothered by it, or by 
the lack of a flood-fill function. To me, these are 
uncharacteristically odd omissions from PIL.

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


Re: Setting the corner color in rotated PIL images

2005-05-06 Thread rzed
[Following up]

> - Original Message -
> From: "rzed" <[EMAIL PROTECTED]>
> Newsgroups: comp.lang.python
> To: 
> Sent: Sunday, May 01, 2005 1:17 PM
> Subject: Setting the corner color in rotated PIL images
> 
> 
>> I'm using PIL to generate some images which may be rotated at
>> the user's option. When they are rotated, the original image is
>> cropped in the new image (which is fine), and the corners are
>> black (which is not, in this case). I can't find any documented
>> way to change the default fill color (if that's what it is) for
>> the corners, and PIL also doesn't seem to support a flood fill.
>> I have created a flood fill in Python, which works but which
>> markedly slows image generation.
>>

"Anthra Norell" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> I just had the same problem the other day. I solved it by
> starting out with an image large enough to retain enough white
> area following the rotation. 
> 
> Frederic
> 

I found another method that doesn't require the larger size and 
cropping :) but does require two copies of the original image :( 
(sort of).

I copy the image and rotate the copy, then I create an all-white 
image of the same size as the original and rotate it by the same 
amount. Then I use ImageChops composite() to combine the rotated 
copy, the original copy, and the black-and-white version 
(parameters in that order). The black corners of the b/w version 
serve as a mask to paste the original corners onto the copy. 

It still seems like a lot of trouble to go to, but I don't think 
there is a ready solution otherwise. I think there's a C-code 
memset of all zeroes that underlies the black corners thing, and 
that's not likely to change.

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


Re: Setting the corner color in rotated PIL images

2005-05-03 Thread rzed
"Anthra Norell" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

[in response to:
>> I'm using PIL to generate some images which may be rotated at
>> the user's option. When they are rotated, the original image is
>> cropped in the new image (which is fine), and the corners are
>> black (which is not, in this case). I can't find any documented
>> way to change the default fill color (if that's what it is) for
>> the corners, and PIL also doesn't seem to support a flood fill.
>> I have created a flood fill in Python, which works but which
>> markedly slows image generation.]

> I just had the same problem the other day. I solved it by
> starting out with an image large enough to retain enough white
> area following the rotation. 

Well, that's a workaround I could try, but I'm half-hearted about 
it. I don't like to think that it's *required*. Another possible 
solution is to make the outer portion black, so the rotation seems 
to do the right things, but in the cases I'm dealing with, that's 
either out or more trouble than it's worth. I can haul the rotated 
images into a paint program and manually touch up the corners, too, 
but I don't like to have to do that either.

It seems strange that there wouldn't be some way to change the 
black to another color, or (maybe just as good) to transparent. PIL 
is so useful that it strikes me as an aberrant oversight. More 
likely, there *is* a better way, but I just don't know it and can't 
find it in the docs. 

-- 
rzed

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


Setting the corner color in rotated PIL images

2005-05-01 Thread rzed
I'm using PIL to generate some images which may be rotated at the 
user's option. When they are rotated, the original image is cropped 
in the new image (which is fine), and the corners are black (which 
is not, in this case). I can't find any documented way to change 
the default fill color (if that's what it is) for the corners, and 
PIL also doesn't seem to support a flood fill. I have created a 
flood fill in Python, which works but which markedly slows image 
generation. 

Can anyone suggest a better way to set the color of the corners? 

All I really need in this case is that they be a solid color, the 
same color they were before being rotated. 

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


Re: help please

2005-02-21 Thread rzed

"gargonx" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Even if i put it in exactly the way you did:
>
> >>> import re
> >>> charmatcher = re.compile(r' [A-Z] [\d]?')
> >>>
> >>> ext = dict(D="V1", O="M1", G="S1")
> >>> std = dict(S="H")
> >>>
> >>> decode_replacements ={}
> >>> decode_replacements.update([(std[key], key) for key in std])
> Traceback (most recent call last):
>   File "", line 1, in ?
> AttributeError: keys


Works with 2.4, but not with 2.3.4:

Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> charmatcher = re.compile(r' [A-Z] [\d]?')
>>>
>>> ext = dict(D="V1", O="M1", G="S1")
>>> std = dict(S="H")
>>>
>>> decode_replacements ={}
>>> decode_replacements.update([(std[key], key) for key in std])
>>>
>>> print decode_replacements
{'H': 'S'}



Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> charmatcher = re.compile(r' [A-Z] [\d]?')
>>>
>>> ext = dict(D="V1", O="M1", G="S1")
>>> std = dict(S="H")
>>>
>>> decode_replacements ={}
>>> decode_replacements.update([(std[key], key) for key in std])
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: keys
>>>
>>> print decode_replacements
{}




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


Re: namespaces module (a.k.a. bunch, struct, generic object, etc.) PEP

2005-02-11 Thread rzed
Jeremy Bowers <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> On Fri, 11 Feb 2005 22:23:58 +1000, Nick Coghlan wrote:
>> This is one of the reasons why Steven's idea of switching to
>> proposing a new module is a good one. It then provides a
>> natural location for any future extensions of the idea such as
>> Records (i.e. namespaces with a defined set of legal fields)
>> and NamedTuples and NamedLists (i.e. namespaces with a defined
>> field order) 
> 
> I'm not very good at reading Guido's mind, but it might be worth
> feeling out whether mentioning this will improve the chances of
> this passing or not, because while I do not know, can not know,
> and am not trying to predict, it is at least possible that Guido
> may feel as I have been: That this proposal on its own isn't
> that exciting, but as the foundation of some *other* standard
> functionality as described it might be very good. In that case
> that should be emphasized. 
> 
> See, now it still doesn't make me jump up and down because I can
> write what I need fairly easily, but it would be a great boon to
> beginners or people who just want to do work and re-write this
> again, but slightly differently, and would also provide some
> standardization where otherwise we all roll our
> not-quite-similar-enough implementations, which would help us
> read each other's code. 
> 
> Y'all are bringing me around, slowly but surely :-)

Yes, it seems that the main benefit is to provide a Python-standard 
way of doing something that many individuals see as useful. Like 
many others, I've implemented my own variation (a class I call 
Data) to do essentially the same thing as the bunch/namespace 
proposal. If there had already been an existing standard way to do 
it, I would at most have needed to subclass the standard method. 

I would bet that subclassing is *still* going to be common, though, 
as each of us individually roll our own version to get that one 
vital feature the standard doesn't cover (for me, it's update with 
numerous other types), so the net effect may actually not be all 
that different from what happens now. Still, I could happily give 
up some features as long as the functionality is still available 
and presuming I intended the code for public consumption, and for 
that, Namespace would be most useful. 

Though I'd like it to have a shorter name. I'm lazy.

-- 
rzed

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


Re: Python versus Perl ?

2005-02-11 Thread rzed
"Mauro Cicognini" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> 
> Alex Martelli wrote:
> 
>> URK -- _my_ feeling is that we have entirely *too many* options
>> for stuff like web application frameworks, GUI toolkits, XML
>> processing, 
> ...
>>
>>
>> Alex
> 
> I entirely second that.
> 
> More, I'd heartily welcome an authoritative word on which to
> focus on for each category... I hate to see scarce resources
> wasted. 
> 

Alex also suggested that a revival of the anygui interface would be 
a Good Thing. I would certainly love to see that.

It seems to me that Python should in fact include either anygui or 
an equivalent to it as part of its core. Then to interface with a 
given GUI package, it would be necessary to create a wrapper that 
maps the wrapper's API to that standard Pythonic API. More work for 
the package maintainers, and not easy to do in some cases, but for 
the Python community it would be a huge gain. The same argument 
could be made for the anydbm interface. 

In both cases, the interface should not hinder the ability of a 
developer to access any part of the package API, which implies that 
parameters must be flexible. Maybe this is a strong use case for 
bunch/data/namespace arguments and return values.

-- 
rzed

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


Re: Curses on Windows

2005-02-08 Thread rzed
"Martin Miller" <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

> I just tried the flangy.com link and it appears to be OK now.
> 
> Martin
> 
> 
> Peter wrote:
>> ...
>> One reply (in fact the only reply - thanks Tim Golden) suggested I
>> look at http://flangy.com/dev/python/curses/
> 

But this one is still forbidden, at least for me:
http://flangy.com/dev/python/curses/files/wcurses-0.1-py2.4.zip

-- 
rzed

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


Re: ConfigParser - add a stop sentinel?

2005-01-12 Thread rzed
Larry Bates <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

[responding to the idea of placing a sentinel in an ini file, 
and modifying ConfigParser to stop receiving input when it is
encountered]:

> You should probably consider NOT doing what you suggest.  You
> would need to do some rather extensive work so you can support
> the .write method of ConfigParser.  With a little ingenuity
> I've been able to user ConfigParser to support some very
> different and complex syntaxes on different projects.  If this
> won't work, just have two different (separate) files.
> 
> If you are dead set on combining these two, put your foreign
> syntax lines into the file as comments.  ConfigParser will
> not process them, and you can have some other class extract
> only the comments and parse them independently.

I'm not sure I understand what you mean about the .write method of 
ConfigParser. I'm not trying to alter the *behavior* of 
ConfigParser at all, just giving it an alternative end of input 
(apart from EOF). And I'm not trying to replicate ConfigParser in 
my own configuration stuff. If I were, I'd just use ConfigParser. 

What I am doing is specifying a cluster of parameters on a single 
line in a compact, comma-separated form. I can easily split each 
parameter line and use the appropriate values, but it's not 
something ConfigParser is designed to accommodate, as far as I can 
tell.

I don't want to put them into comments (though I could, I see), 
because I comment my own lines with hashmarks as well. I suppose I 
could lead off with double hashmarks and just strip off the first 
to get the desired effect, but it's an annoyance and it doesn't 
contribute to understanding what the config file is supposed to do. 
Still, as a workaround, it is something to consider.

I just can't imagine that I'm the first person in history to have 
stumbled on such a use case, though. If ConfigParser would have a 
way to just take in raw data line-by-line within some group 
heading, that would work for this case just as well, and it seems 
to me that *that* might be useful in some other applications also 
... though that's not what I'm talking about in this instance.
 
-- 
rzed

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


ConfigParser - add a stop sentinel?

2005-01-12 Thread rzed
I am working with PythonCard in one of my apps. For its purposes, it 
uses an .ini file that is passed to ConfigParser. For my app, I also 
need configuration information, but for various reasons, I'd rather 
use a syntax that ConfigParser can't handle.

I know I can maintain two separate configuration files, and if I have 
to I will, but I'd rather avoid that, if possible, and a solution 
that suits my purposes is quite straightforward. I insert a sentinel 
in the ini file and modify my local ConfigParser's _read method to 
stop accepting input when it encounters that value. I handle my app's 
portion of the configuration myself.

This all works fine, but I was wondering whether it might be 
worthwhile to add a standard stop flag in ConfigParser itself. Am I 
the only one with this sort of use case? If there were a standard way 
of doing this, I'd much rather use that, particularly if I ever have 
reason to distribute the app elsewhere.
-- 
rzed

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


Re: Lambda going out of fashion

2004-12-23 Thread rzed
Jp Calderone <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> On Thu, 23 Dec 2004 13:36:08 GMT, rzed <[EMAIL PROTECTED]> wrote:
>>Stephen Thorne <[EMAIL PROTECTED]> wrote in
>> news:[EMAIL PROTECTED]: 
>> > [snip]
>> > 
>> > {
>> >  'one': lambda x:x.blat(),
>> >  'two': lambda x:x.blah(),
>> > }.get(someValue, lambda x:0)(someOtherValue)
>> > 
>> > The alternatives to this, reletively simple pattern, which is
>> > a rough parallel to the 'switch' statement in C, involve
>> > creating named functions, and remove the code from the
>> > context it is to be called from (my major gripe).
>> >
>> > [snip]
>> 
>> Not addressing lambdas per se, but something similar to your
>> pseudo- switch statement can be done without using them at all.
>> One way might be to use a function dictionary wrapped in an
>> accessor function, such as this:
>> 
>> def dofns(key):
>> fd2 = {
>> 0:'print "Key 0"',
>> 1:'print "one"',
>> 4:"\n".join(['for ix in range(15):',
>>   '  print "%s%d" % (" "*ix,ix)']),
>> }
>> try:
>> exec(fd2[key])
>> except KeyError:
>> print 'Key',key,'not found'
>> 
> 
>   I hate to be nasty, but *ugh* what a horrible way to start the
>   day. 
> 
>   There are so many things wrong with this.
> 
>   By exec'ing code strings you lose compile-time _syntax_ 
> checking.  I'm all for dynamicism, but it really is nice to let
> the compiler do _something_ things for you.
> 
>   By exec'ing code strings you slow down the entire function 
> by forcing a slower name-lookup code path in the interpreter.
> 
>   By exec'ing code strings you lose the ability to pass values 
> back to your caller (oh, you could "return" in one of those, but
> *ugg* that'd be even more terrible, and probably not what you
> want in most cases, since it doesn't let you get at the value
> except from your caller.  you could also set names in the local
> namespace but that's pretty messed up too, python already has a
> function return convention, making up your own is no fun).

Thanks for your comments. I'll not argue that I would actually put 
exactly this code into anything I intended for public consumption; 
it was to illustrate that there were in fact alternatives to 
lambda. 

In point of fact, though, there might be reasons to do something 
similar (addressing at least a couple of your objections). I don't 
think speed of execution is going to be a factor unless the main 
processing in the program centers on this snippet. It's a way to 
dummy up a switch statement, and while that could mean it was 
central to the program, it seems to me more likely to be relatively 
peripheral. 

In a switching application, the dynamic code shown would more 
likely be function invocations, but it could on occasion be useful 
to implement a script processor (I've used them for various 
reasons). Generally they seem most useful for interacting with 
humans (and hence with human speed limitations). 

One class of applications where such a technique could be useful 
would be in allowing various groups to access a database and 
perform operations on the data specific to their function. Dynamic 
searches, for instance, ad hoc reporting and the like. Not all 
groups would have the same needs or privileges, and using separate 
function tables is one way to limit activities to a specified 
range. 

It's fairly trivial to allow passing and returning data; the main 
difficulty (apart from security concerns) is choosing the 
convention to use. 

> 
>   There are probably more reasons this is bad too.
> 
>   Even using `def' to define a function for each of these would
>   be 
> preferable.
> 
>   Aside from that, exec() isn't a function.  You "exec foo", not
> "exec(foo)".  The latter works simply because parens act as to
> set precedent instead of as part of function call syntax when
> used this way.
> 
>   Also, you should do the dictionary lookup first, in a
>   try/except, 
> and then execute it later, _outside_ the try/except, otherwise
> you risk masking KeyErrors from exec'd code.
> 
>   Jp
> 

Good points, which I'll take to heart when I'm putting this stuff 
into production code. 
-- 
rzed

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


Re: Switch statement (was: Lambda going out of fashion)

2004-12-23 Thread rzed
Skip Montanaro <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> 
> Stephen> {
> Stephen>  'one': lambda x:x.blat(),
> Stephen>  'two': lambda x:x.blah(),
> Stephen> }.get(someValue, lambda x:0)(someOtherValue)
> 
> One thing to remember is that function calls in Python are
> pretty damn expensive.  If x.blat() or x.blah() are themselves
> only one or two lines of code, you might find that your "switch"
> statement is better written as an if/elif/else statement. 
> You're making potentially three function calls (get(), lambda
> and x.blat() or x.blah()) to perform what might only be a small
> handful of inline statements.  I'll ignore the readability cost
> of your solution vs. an if statement.
> 
> Stephen> So, the questions I am asking are: Is this okay
> with everyone? 
> 
> Sure.  I'll adjust.
> 
> Stephen> Does anyone else feel that lambda is useful in this
> kind of Stephen> context?
> 
> It's useful in this sort of context.  It will probably always be
> limited to single expressions, which will always leave it a
> second-class citizen in Python.  Interestingly enough, lambda in
> the Lisp world has the same limitation, however, since Lisp code
> is nothing but a series of s-expressions, that's not a problem.
> 
> Stephen> Are there alternatives I have not considered?
> 
> I've never seen a situation where if/elif/else wasn't adequate
> or was less clear than the many attempts at switch-like
> behavior. 
> 
> Folks (in general), there is still an open PEP on a switch
> statement for Python.  It's been idle since late 2001:
> 
> http://www.python.org/peps/pep-0275.html
> 
> It would help if interested people were to take a look at it and
> identify open issues.  If you google for pep 275 you will
> probably find relevant python-dev discussions from the 2001/2002
> timeframe.  Thomas Wouters' patch for the interpreter would also
> need to be resurrected and brought up-to-date.  I not longer
> remember why the PEP stalled. 
> 

It seems to me that it was regarded as misguidod.

-- 
rzed

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


Re: Lambda going out of fashion

2004-12-23 Thread rzed
Stephen Thorne <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Hi guys,
> 
> I'm a little worried about the expected disappearance of lambda
> in python3000. I've had my brain badly broken by functional
> programming in the past, and I would hate to see things suddenly
> become harder than they need to be.
> 
> An example of what I mean is a quick script I wrote for doing
> certain actions based on a regexp, which I will simlify in this
> instance to make the pertanant points more relevent.
> 
> {
>  'one': lambda x:x.blat(),
>  'two': lambda x:x.blah(),
> }.get(someValue, lambda x:0)(someOtherValue)
> 
> The alternatives to this, reletively simple pattern, which is a
> rough parallel to the 'switch' statement in C, involve creating
> named functions, and remove the code from the context it is to
> be called from (my major gripe).
>
> So, the questions I am asking are: 
> Is this okay with everyone? 
> Does anyone else feel that lambda is useful in this kind of
> context? Are there alternatives I have not considered?
> 

Not addressing lambdas per se, but something similar to your pseudo-
switch statement can be done without using them at all. One way might 
be to use a function dictionary wrapped in an accessor function, such 
as this:

def dofns(key):
fd2 = {
0:'print "Key 0"',
1:'print "one"',
4:"\n".join(['for ix in range(15):',
'  print "%s%d" % (" "*ix,ix)']),
}
try:
exec(fd2[key])
except KeyError:
print 'Key',key,'not found'

The keys can as easily be strings, of course. One virtue of this 
method is that it allows multi-line statements and looping (as in fd2
[4]).

Now the actual 'switch' statement becomes as simple as:
dofns(key)

If there are parameters involved, this solution becomes a little 
tackier. One way might be something like:

def dofns(key,**kws):
fd2 = {
0:'print "Key 0"',
1:'print "one"',
2:"\n".join(['n=kws["name"]','x=kws["x"]',
'y=kws["y"]','print "%s:"%n,x,y']),
3:"\n".join(['val=kws["x"]*7 + kws["y"]',
'print kws["x"],kws["y"],val']),
4:"\n".join(['for ix in range(kws["x"]):',
'  print "%s%d" % (" "*ix,ix)']),
5:'exec(fd2[3])',
6:"\n".join(['print kws["z"],',
'dofns(3,x=13,y=22)']),
}
try:
exec(fd2[key])
except KeyError:
print 'Key',key,'not found'


# switch (key kwdparms)
for key in [0, 1,2,3,4,5,6,7]:
dofns(key,name='Gladys',y=50,x=8,z=34)

You could remove the function dictionary from the wrapper and use it 
similarly to your example, but I find that less readable. 
exec({
multi-line dictionary definition
}[key] parms) # what were we doing again? Oh! exec!

Anyway, for those who use lambdas, this approach is likely to be 
unappealing. For those who find lambdas puzzling, it may be an 
alternative, at least for a way to handle the switch equivalent.

-- 
rzed

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