Re: Is Python like VB?

2005-03-16 Thread Ville Vainio
> "Cappy" == Cappy2112  <[EMAIL PROTECTED]> writes:

Cappy> VB has a much better IDE than the IDE's for Python,
Cappy> although Eric3 is one of the best, and is absolutely free.

Eric3 is not easily available for win32, due to current state of Qt
licensing (will change with Qt4 I think).

Cappy> There are many gui toolkits/frameworks for Python, but the
Cappy> foreunners are pyQT, wxPython, pyGTK, and TK/Tkinter.

On windows it might make sense to choose wxPython, though I've heard
some good stuff about new versions of pyGTK as well.

People coming from VB background probably also appreciate the ability
to draw the UI in point&click style:

http://gazpacho.sicem.biz/
http://wxglade.sourceforge.net/

Unfortunately these seem to still be a tad rough around the edges...

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


HELP: Bitmaps Using Tkinter ?

2005-03-16 Thread Peter Moscatt
When placing an image onto a button object with:

b=Button(root,bitmap="@image.xbm")

Do I have to use a XBM or are there other formats that I can use ?

Pete

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


Re: Getting current variable name

2005-03-16 Thread Ron
pl wrote:
Hi all,
I followed the mails entitled 'How to turn a variable name into a
string?' in march 2005 posts as I have a similar problem.
Use the locals() function instead of globals().
Thanks by the way, I was wondering how to do this also, your post, and 
Daniel pointing out 'is', helped me work this out.  There should be an 
easier way that doesn't require stepping though the name list.

This doesn't use lists in the same way, but I think it answers your 
question.

def getvinfo(vars, v):
"""
vars is locals()
v is [varable]
Use an one item list to pass single varables by reference.
"""
for n in vars.keys():
if vars[n] is v[0]:
return n, v[0], type(v[0])
a = 101
b = 2.3
c = True
print getvinfo(locals(), [a])
print getvinfo(locals(), [b])
print getvinfo(locals(), [c])
>>>
('a', 101, )
('b', 2.2998, )
('c', True, )
This could be useful for printing error messages and debugging info.
Ronald Adam
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lisp-likeness

2005-03-16 Thread Ville Vainio
> "Michele" == michele simionato <[EMAIL PROTECTED]> writes:

Michele> But then why he agreed to have the loop variable
Michele> disappear outside a generator comprehension?  I think
Michele> there is something more than a backward compatibility
Michele> concern.

With normal for-loop (as opposed to genexps and LCs), the "last" value
of the loop variable might be useful outside the loop if the loop was
exited prematurely through 'break' statement or exception.

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


Re: Is Python like VB?

2005-03-16 Thread Harlin Seritt
"Would Python meet our requirements? "

Yes and no. Because Python is a very high-level language and
dynamically typed it is easy to learn. Python doesn't make use of
pointers but you are able to write object-oriented code (as opposed to
just being object-friendly like Visual Basic is). You will find that on
its own you won't be able to do any Office macro scripting although
there are several packages that will give you added functionality like
access to Com+ objects (see win32 modules by Mark Hammond). Now, this
may require more work than using VBA but it *is* doable. The com
portion of the win32 modules can enable one to create even a
macro-language unto itself!

Python is very powerful. There are many 3rd party modules and
frameworks (Zope, CherryPy). Also, there are many GUI toolkits
available for it (wxWindows, GTK, QT, Tk and on and on) and you can
also use it as a wrapper to write and compile to Java bytecode (see
Jython). The problem for you, however, is it may or may *not* meet
every requirement. For that you'll have to find out for yourself. I
suggest downloading Python and giving the Python tutorial a whirl and
then taking a look at other Python-related stuff:

[For programmers:] http://docs.python.org/tut/tut.html
[For non-programmers:] http://honors.montana.edu/~jjc/easytut/easytut/
[Win32 stuff:] http://starship.python.net/crew/mhammond/
[Tk 'Tkinter':]
http://www.pythonware.com/library/tkinter/introduction/
[wxPython:]http://www.wxpython.org/
[PyGTK:]   http://www.pygtk.org/

Purusing these links will give you a very good idea of whether Python
is right for you. Naturally we'd all like to say 'YES Python is good
for you!' but you have to investigate for yourself.

Good luck!

Harlin Seritt

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


Calling the C API from Python and Python program from same C API - bidirectional

2005-03-16 Thread Praveen, Tayal (IE10)
Hi Guys,

I am having problems in the following C API program where myOtim_system is
callable from python function. The module is listed below - 

static PyObject *
myOptim_system(PyObject *self, PyObject *args)
{
const char *command;
double u0, v0, u1, v1, u2, v2, u3, v3;
int sts;

/* variables */
PyObject *pstr, *pmod, *pdict, *pfunc, *pargs;
char * cstr;
char *dummy = "Test";
char *x = "x = ";


if (!PyArg_ParseTuple(args, "s", &command))
return NULL;

/* convert them to the doubles */
sscanf(command, "%lf %lf %lf %lf %lf %lf %lf %lf", &u0, &v0,
&u1, &v1, &u2, &v2, &u3, &v3);

sts = (int) (u0+v0+u1+v1+u2+v2+u3+v3);

/* trying to call the python program from C */
/*
The module name is test2_module and the function name is
cv_calc_func
- get test2_module.cv_calc_func
*/
pmod = PyImport_ImportModule("test2_module");
pdict = PyModule_GetDict(pmod);

/* convert to the PyObject */
pfunc = PyObject_GetAttrString(pmod, "cv_calc_func");
pargs =  Py_BuildValue("s", dummy);
pstr = PyEval_CallObject(pfunc, pargs);

PyArg_Parse(pstr, "s", &cstr);
printf("%s\n", cstr);

Py_DECREF(pmod);
Py_DECREF(pstr);
Py_DECREF(pfunc);
Py_DECREF(pargs);


return Py_BuildValue("i", sts);

}

In the same module I am trying to call the python program from C API. That
python program is called test2_module.py. It is listed below - 

import string

message = 'Hi I am here'

def cv_calc_func(dummy):
s = "warning" + `dummy`
return s


-
It contains a method called cv_calc_func(). So now the idea must me clear. I
would need to communicate bi-directionally, i.e. from python to C and C to
python. This example is inspired by the fact that we use the C func from
Numerical recepies in C corresponding to lets say some optimization
algorithm. So that we don't re-invent the wheel in python. So we call a C
API from python. But in the optimization the objective function value must
be returned from a python program, so from C API I should be able to call a
python program and then integrate it with my optimization algorithm.

In this example I have tried to use "PyEval_CallObject()" within the
"myOptim_system" C API function but it reports memory error. But when I call
it from main() it doesn't report any errors.
Just wondering what do I do here?

-regards
Prav 


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


Re: Is Python like VB?

2005-03-16 Thread Cappy2112
First of all, discontinuing VB doesn't mean you have to stop using it.
I worked on a project which was compiled with Visual C 1.52, for many
years after it was not supported. The project is used by nearly every
engineer at the company where I work.
We are still devleoping the project I work on now in VB6, and have no
reason to bail.
For new projects, it would make sense to look into VB.net or some
alternative.

Python has classes, but not templates. However, you don't have to use
classes in your program, but it will make life easier if you learned
them.

Python's classes are not as complicated as C++, it's a much better
language to learn from.

VB has classes too, and if you haven't used them in your programs, then
there's a good chance you can program that way with Python too, but I
wouldn't make a point of it.

VB has a much better IDE than the IDE's for Python, although Eric3 is
one of the best, and is absolutely free.

VB's ide is it's strongpoint, not the language itsself.

If you need to do Gui's then it is extremely usefull to learn the
basics of classes, your code will be much simpler in the long run.

There are many gui toolkits/frameworks for Python, but the foreunners
are pyQT, wxPython, pyGTK, and TK/Tkinter.

You don't have to worry about pointers though :-)

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


Re: code for Computer Language Shootout

2005-03-16 Thread Raymond Hettinger
> > . import string, itertools, sys
> > .
> > . t = string.maketrans('ACBDGHKMNSRUTWVYacbdghkmnsrutwvy',
> > .  'TGVHCDMKNSYAAWBRTGVHCDMKNSYAAWBR')
> > .
> > . for h,b in itertools.groupby( file(sys.argv[1]), lambda x: x[0] in
> > ">;" ):
> > . if h:
> > . print "".join(b),
> > . else:
> > . b = "".join(b).translate(t, "\n\r")
> > . print "\n".join( b[-i:-i-60:-1] for i in xrange(1, len(b),
> > 60) )
> >
>
> I benchmarked this, btw - it ran in the same amount of time as the other
> solution. It does have the advantage of being significantly fewer lines of
> code; I suppose that itertools.groupby, while unexpected to someone from a
> language without such niceties in the standard library =), is a better
> solution than duplicating the code (or the function call) to translate,
> reverse, and format the string.

While the use of groupby() is brilliant, I prefer the previous version as a
demonstration of beautiful, general purpose, plain Python code running at
full-speed.


Raymond Hettinger


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


Re: Itertools wishlists

2005-03-16 Thread Raymond Hettinger
>itertools.window() with n=2 got rejected.  Almost all proposed uses had better
> >solutions (such as an accumulator variable or fibonacci sequence style logic:
> >a, b = b, a+b).  Writing it in C afforded only small speed advantage over a
> >solution using izip() and tee().

[Christos TZOTZIOY Georgiou]
> Speed or C implementation was not my objection.
 . . .
> Just make it
> readily available.  I volunteer for a patch if we agree on it[1].

No thanks.  A patch was developed, discussed, and rejected long ago. The main
reason was that existing approaches were often better (at least in the context
of the use cases that we reviewed).  Performance was mentioned because that is
sometimes used to justify a new tool.  In this case, that justification was not
strong.


> None of the
>
itertools.(queue|roundrobin|accumulate|multi_gen|remove_value|eq|consume|ilines)
> that you reference exists as a recipe in the docs.

FWIW, the recipe for roundrobin is at:
http://docs.python.org/lib/deque-recipes.html .

The only other one worth further discussion is iterequals().  I held-off
publishing that one because the opportunites for error were too great (see the
previous post for details).



> Did I make you believe I cared about the fate of any function judged unworthy
> even for the documentation?

No.  My note was mainly for the benefit of those who had an interest in what
type of ideas had been discussed and the reasoning behind their
inclusion/exclusion.  It needed to be documented somewhere and the newsgroup
discussion on a couple of proposals provided an opportunity to put those notes
on record.



> I'm just whining that putting recipes in the docs as an 'extended
> toolset' instead of in a module is a joking compromise...

Not really.  The recipes have several uses and none of them are compromises.

Firstly, they serve as a proving ground which helps inform further development.
As a recipe, they can be readily altered, improved, or removed without breaking
anything.  However, once I include them as part of the module, the API gets
frozen, as do any accidents of implementation.  Once released, the process of
making repairs or alterations becomes slow and painful.  Over time, some of the
recipes will disappear. some will evolve, and some will work their way into a
module (witness any() and all() as recent examples).

By way of comparision, consider the evolution of set()/frozenset() which went
through stages as recipes, as a PEP, then as Python module, and finally as C
coded built-ins.  That multi-stage process was deliberate and resulted in the
final version being excellent.  Similarly, many new decorators are going to
start their lives as wiki entries or recipes.  Ultimately, some will make it
into the standard library.  It would be a mistake to make that transition too
quickly.

The other purpose of the itertool recipes is to serve as a teaching tool showing
how to combine the tools and how to integrate them with other Python code.  IMO,
most of the recipes are more useful in this capacity than as immediate solutions
to particular problems.



Raymond Hettinger


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


Re: wxPython vs. pyQt

2005-03-16 Thread Simon John
I used to be a wxPython lover, but it was mainly due to the crappy PyQt
licensing terms, rather than any merits of wx (although I like the
native LnF).

After trying to do a large-ish project using wxPython, I found that I
was limited by the lack of widgets and the layout system.

My latest project was in PyQt, after Trolltech announced that Qt4 will
have a GPL version for Windows (and Riverbank said they will make a
PyQt to go with it eventually).

I usually hate visual GUI IDEs, but I found QtDesigner to be a real
asset, much better than wxDesigner or VisualStudio. The threading
implementation also seems superior (easier?) to Python's own too, and
making custom widgets is easy enough, even with a Python wrapper.

Also, the Cygwin guys have ported the GPL/Linux Qt to Windows, so you
can use that for Qt3.3 until Trolltech come up with Qt4.

Links:
http://kscraft.sourceforge.net/convert_xhtml.php?doc=pyqt-windows-install.xhtml
http://kde-cygwin.sourceforge.net/qt3-win32/
http://www.pycs.net/lateral/stories/27.html

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


Linking problems under irix6 with embedded Python2.4

2005-03-16 Thread Wolfgang
I have a problem with linking my CPP Code under a irix6 machine (sgi,
UNIX). In my CPP code I use some Functions which are written in
Python. So its a kind of CPP wrapper for my Python functions In my
Python Code I use threads to communicate over the network and stuff
like this. Compilation and linking are working very well under Windows
and Linux with the same code. Under the sgi, UNIX machine some errors
occur and I don't no why. Following version are used:
Python2.4
gcc version 3.0.4
 
For linking I'am using following statement:
g++ -v -lm -lpthread -lsocket -lnsl  -ldl  -DNDEBUG -g -O3 -Wall
-fno-strict-aliasing -fPIC -Xlinker
-I/work/efs/rohrache/python24/Python2.4/local/lib/python2.4/lib-dynload
DynArray.o  Interface.o sim_calc.o -o simcalc
/work/efs/rohrache/python24/Python-2.4/libpython2.4.a

The linking options, I take from the makefile which Python produces
during the installation process. Following output occur.

=> ... 
Reading specs from /usr/freeware/lib/gcc-lib/mips-sgi-irix6.5/3.0.4/specs
Configured with: ../configure --prefix=/usr/freeware
--enable-version-spec
ific-runtime-libs --disable-shared --enable-threads --enable-haifa
Thread model: single
gcc version 3.0.4
 /usr/freeware/lib/gcc-lib/mips-sgi-irix6.5/3.0.4/collect2
-call_shared -n
o_unresolved -init __do_global_ctors -fini __do_global_dtors
-_SYSTYPE_SVR
4 -woff 131 -n32 -o simcalc /usr/lib32/mips3/crt1.o
/usr/freeware/lib/gcc-
lib/mips-sgi-irix6.5/3.0.4/crtbegin.o
-L/usr/freeware/lib/gcc-lib/mips-sgi
-irix6.5/3.0.4 -L/usr/bin
-L/usr/freeware/lib/gcc-lib/mips-sgi-irix6.5/3.0
.4/../../.. -lpthread -lsocket -lnsl -ldl
-I/work/efs/rohrache/python24/Py
thon2.4/local/lib/python2.4/lib-dynload DynArray.o Interface.o
sim_calc.o
/work/efs/rohrache/python24/Python-2.4/libpython2.4.a -lstdc++ -lm
-dont_w
arn_unused -lgcc -warn_unused -L/usr/lib32/mips3 -L/usr/lib32
-dont_warn_u
nused -lc -warn_unused -dont_warn_unused -lgcc -warn_unused
/usr/freeware/
lib/gcc-lib/mips-sgi-irix6.5/3.0.4/crtend.o /usr/lib32/mips3/crtn.o
(null): WARNING 1  : Unknown option:
I/work/efs/rohrache/python24/Python2.
4/local/lib/python2.4/lib-dynload (ignored).
ld32: WARNING 84 : /usr/lib32/libpthread.so is not used for resolving
any
symbol.
ld32: WARNING 84 : /usr/lib32/libsocket.so is not used for resolving
any s
ymbol.
ld32: WARNING 84 : /usr/lib32/libnsl.so is not used for resolving any
symb
ol.
ld32: WARNING 84 : /usr/lib32/libdl.so is not used for resolving any
symbo
l.
ld32: ERROR   33 : Unresolved text symbol "pthread_detach" -- 1st
referenc
ed by /work/efs/rohrache/python24/Python-2.4/libpython2.4.a(thread.o).
Use linker option -v to see when and which objects, archives
and d
sos are loaded.  
ld32: INFO152: Output file removed because of error.
collect2: ld returned 2 exit status

The warnings are no problem to eliminate, but the error message is
very strange.
I don't know how i can handle this problem. I tried alot of additional
link options but I can find no realy solution. Are there some ideas.

thank's alot.
Wolfgang
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Turning String into Numerical Equation

2005-03-16 Thread Steven Bethard
Giovanni Bajo wrote:
Then, I should start my usual rant about how is really sad to send patches to
Python and have them ignored for years (not even an acknowledge). Really sad.
This is why I'm not going to do that again.
I don't know the last time you read python-dev, but a number of the 
senior Python folks have agreed to an exchange: if you provide reviews 
of 5 patches (posted on their trackers and summarized as a post to 
python-dev) they will promise to review your patch (and presumably close 
it with some resolution).

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


Is Python like VB?

2005-03-16 Thread Mike Cox
As you may or may not know, Microsoft is discontinuing Visual Basic in favor
of VB.NET and that means I need to find a new easy programming language.  I
heard that Python is an interpreted language similar to VB.  This means that
it doesn't have all the hard stuff like pointers, classes and templates like
C, C++ and assembly language.

Where I work we use  Microsoft Office with a lot of customization using
Visual Basic.  I would like to switch to Python to do it since VB is being
discontinued.  Would Python meet our requirements? I need to make lots of
GUI applications (message boxes, forms, etc.) and do the underlying business
logic too.

Thanks in advance.


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


ANNOUNCE: wxPython 2.5.4.1

2005-03-16 Thread Robin Dunn
Announcing
--
I'm pleased to announce the 2.5.4.1 release of wxPython, now available
for download at http://wxpython.org/download.php
What is wxPython?
-
wxPython is a GUI toolkit for the Python programming language. It
allows Python programmers to create programs with a robust, highly
functional graphical user interface, simply and easily. It is
implemented as a Python extension module that wraps the GUI components
of the popular wxWidgets cross platform library, which is written in
C++.
wxPython is a cross-platform toolkit. This means that the same program
will usually run on multiple platforms without modifications.
Currently supported platforms are 32-bit Microsoft Windows, most Linux
or other Unix-like systems using GTK or GTK2, and Apple Macintosh OS
X.
Changes in 2.5.4.1
--
wx.Sizer Add, Insert, and Prepend functions now return a reference to the
wx.SizerItem that was added to the sizer, and the wx.SizerItem has a
GetRect accessor to give the position of the item on the parent window.
Added wx.Sizer.GetItem method which returns the wx.SizerItem for the given
wx.Window, wx.Sizer or position index.
wxMSW: wx.RadioButtons in the same group no longer have to be
consecutive (there may be intervening controls). Without this fix, an
out-of-sync assert is generated when clicking on a radio button and
then calling GetValue().
Some XRC changes:
- Added 'icon' property to wxFrame and wxDialog
- No longer ignores menu bitmaps on non-MSW platforms
- Notebook page bitmaps are now supported
- added system colours and fonts support (based on patch #1038207)
wxMSW: fix for [ 1052989 ] TextCtrl.SetBackgroundColour(wx.NullColour)
bug.
Added wx.PasswordEntryDialog analagous to wx.TextEntryDialog, allows
detecting entering an empty string vs. cancel unlike the
wx.GetPasswordFromUser dialog function.
OGL patch from Shane Holloway:
Two simple problems found in the new python ogl code.  First is
the patch for _canvas.py.  Essentially::
dx = abs(dc.LogicalToDeviceX(x - self._firstDragX))
dy = abs(dc.LogicalToDeviceY(y - self._firstDragY))
was incorrect because (x,y) and (self._firstDragX,
self._firstDragY) are both already in Logical coordinates.
Therefore the difference between the two is also in logical
coordinates, and the conversion call is an error.  This bug
surfaces when you have OGL on a scrollwin, and you are far from
the origin of the canvas.
The second change in _composit.py basically removes the assumption
that the child is in both self._children and self._divisions.
Causes many problems when it's not.  ;)
Fixed GetSaveData and SetSaveData in wx.lib.multisash to not depend on
the default way that class objectss are converted to strings.
Fixed problem in StyledTextCtrl.Set[HV]ScrollBar that could leave the
internal scrollbar visible.
Added wx.StandardPaths which provides methods for determining standard
system paths for each platform.
wxMSW: The window background is now only erased by default if the
background colour or background mode has been changed.  This better
allows the default system themed behaviour to show through for
uncustomized windows.  Explicit support added for using the correct
theme texture for wx.Notebook pages and their children.
wx.Image: Added support for alpha channels in interpolated and
non-interpolated image rotation.  Added ConvertAlphaToMask helper
method for turning shades of grey into shades of alpha and a colour.
wxGTK2: Reimplemented DoDrawRotatedText() by way of a rotation of an
alpha blended text bitmap.  It would be better if Pango could draw
directly into an wxImage (as FreeType can,) but that is for later...
Added wrappers and a demo for the wx.MediaCtrl class, which can play
various forms of audio/video media using native codecs install on the
system.  So far it is only implemented for Windows and OSX.
wxGTK: Patch applied for Freeze()/Thaw() for wxTextCtrtl.
Added "gravity" for splitter window (patch 1046105). Gravity is a
floating-point factor between 0.0 and 1.0 which controls position of
sash while resizing the wx.SplitterWindow.  The gravity specifies
how much the left/top window will grow while resizing.
wxMSW: wx.Slider's C++ implementation rewritten to be more
maintainable and hopefully less buggy.  The position of the labels has
also been changed in order to better comply with Microsoft's examples
of how to use the control.
wxMSW:  Fix wx.TreeCtrl to end label editing if the control loses
focus (a slightly modified patch 1084592.)
Added wx.EXEC_NODISABLE flag for wx.Execute, which will prevent all
the app's windows being disabled while a synchronous child process is
running.
wxMSW: Much work to correct painting (or leaving transparent) of
control backgrounds, properly using background themes on XP, etc.
Fixed a circular reference problem with wx.Timer.  It will now
completely cleanup after itself when the last reference to the timer
is removed.  If you 

Re: RotatingFileHandler and logging config file

2005-03-16 Thread Bengt Richter
On Wed, 16 Mar 2005 20:48:40 -0800, Rob Cranfill <[EMAIL PROTECTED]> wrote:

>news.sydney.pipenetworks.com wrote:
>
>> 
>> You're looking in the wrong place. Try
>> 
>> http://docs.python.org/lib/node333.html
>> 
>
>which isn't quite the page in question, but leads to the closest 
>pertinent page,
>   http://docs.python.org/lib/logging-config-fileformat.html
>which *still* has nothing on RotatingFileHandler.
>
>That's OK, I've given up on the idea of being able to configure a 
>RotatingFileHandler from a config file; I'll do it in my code as a 
>default, and if users want any *other* behavior, they can config *that*.
>
To fish for yourself, go to google and put

RotatingFileHandler site:docs.python.org

in the search slot and click search.

The first hit is 
   http://docs.python.org/lib/node332.html

HTH

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


Re: wxPython vs. pyQt

2005-03-16 Thread Scott Frankel
I have just started using wxPython.  I selected it over pyQT for 
licensing
reasons.  I'm no gui app expert.  But that said, I've found the toolkit
approachable and the user community very helpful.

Scott

On Mar 16, 2005, at 9:11 PM, [EMAIL PROTECTED] wrote:
I've narrowed down my toolkit selection for my project to wxPython and
pyQt, and now i'd like to hear any opinions, war stories, peeves, etc,
about them, particularly from anyone who's used _both_toolkits_. I'm
only mildly interested in the IDEs and UI designers for each, as i
want to do as much as i can in just Xemacs and xterm. Feel free to
rant, rave, pontificate, whatever.
t.i.a.,
E
--
http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list


wxPython vs. pyQt

2005-03-16 Thread eholbroo
I've narrowed down my toolkit selection for my project to wxPython and
pyQt, and now i'd like to hear any opinions, war stories, peeves, etc,
about them, particularly from anyone who's used _both_toolkits_. I'm
only mildly interested in the IDEs and UI designers for each, as i
want to do as much as i can in just Xemacs and xterm. Feel free to
rant, rave, pontificate, whatever.

t.i.a.,
E
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RotatingFileHandler and logging config file

2005-03-16 Thread Rob Cranfill
Peter Hansen wrote:
The missing piece of the puzzle might be the connection
between the 'args' in the config file and the arguments
passed to the __init__ method of the class
Yes, I can puzzle out the constructor args ("constructor", heh heh, must 
be a Java Man) but it's how to get it to do a doRollover() that's in 
question. No sign of support for it in the docs (which your link to 
doesn't elucidate RotatingFileHandler any better than my original) but 
that's OK, see my following message to <[EMAIL PROTECTED]> (what a 
funny name!)

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


Re: RotatingFileHandler and logging config file

2005-03-16 Thread Rob Cranfill
news.sydney.pipenetworks.com wrote:
You're looking in the wrong place. Try
http://docs.python.org/lib/node333.html
which isn't quite the page in question, but leads to the closest 
pertinent page,
  http://docs.python.org/lib/logging-config-fileformat.html
which *still* has nothing on RotatingFileHandler.

That's OK, I've given up on the idea of being able to configure a 
RotatingFileHandler from a config file; I'll do it in my code as a 
default, and if users want any *other* behavior, they can config *that*.

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


Re: How to create stuffit files on Linux?

2005-03-16 Thread James Stroud
Your users are, what me might call, "ignorant luddites".

The built in 'File->Create Archive' command produces a zip file in OSX. I 
propose that zip is indeed the native compressed format. Perhaps you should 
install OS 7.5 on their machines (c. 1993) to make them feel more 
comfortable.

James

On Wednesday 16 March 2005 07:21 pm, Noah wrote:
> The problem is that my users want to see .sit files.
> I know it's sort of silly. Zip files are foreign and frightening to
> them.
> I mentioned zip files, but they didn't want to deal with them.
>
> Is there a native OS X archive or package format?
> Obviously it must have tar and gzip installed, but I wonder
> how a *.tgz file would appear on the desktop or how the
> GUI would handle it.
>
> Yours,
> Noah

-- 
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to create stuffit files on Linux?

2005-03-16 Thread Noah
The problem is that my users want to see .sit files.
I know it's sort of silly. Zip files are foreign and frightening to
them.
I mentioned zip files, but they didn't want to deal with them.

Is there a native OS X archive or package format?
Obviously it must have tar and gzip installed, but I wonder
how a *.tgz file would appear on the desktop or how the
GUI would handle it. 

Yours,
Noah

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


Re: Lisp-likeness

2005-03-16 Thread michele . simionato
But then why he agreed to have the loop variable disappear outside a
generator comprehension?
I think there is something more than a backward compatibility concern.

  Michele Simionato

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


Re: Why tuple with one item is no tuple

2005-03-16 Thread Jeremy Bowers
On Wed, 16 Mar 2005 17:28:51 -0800, James Stroud wrote:

> On Wednesday 16 March 2005 04:45 pm, Robert Kern wrote:
>> > This would be very unambiguous.
>>
>> Not entirely.
>>
>> > Then, the purity would manifest itself the naked comma being an empty
>> > tuple. Think about the zen of:
>> >
>> > Â Â,
>>
>> Is that a tuple or grit on my monitor? Â:-)
> 
> OK, OK, I'll give up on the commas. Maybe we should just use dollar signs :?

No, using symbols like that is bad. Clearly we need a new parser constant,
THE_ZERO_LENGTH_EMPTY_TUPLE. 

We will, of course, have to forbid assigning any other name to that
constant (more language changes) so that people don't start creating their
own inconsistent name... *especially* shorter ones.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python becoming less Lisp-like

2005-03-16 Thread news.sydney.pipenetworks.com
Jeff Shannon wrote:
news.sydney.pipenetworks.com wrote:
More in relation to the original topic, why can't people just ignore 
features they don't understand and may never use directly. 

Because they may get stuck maintaining code that uses those features. 
 Now, I'm generally in agreement with you -- in general, Python features 
that aren't straightforward (e.g. metaclasses) are clearly advanced 
features and aren't likely to be in everyday code.  I'm okay with just 
knowing that metaclasses exist, and having a vague idea of how one would 
use them.

But the more features that some people ignore, the more that they tend 
to write in a customized dialect that's a subset of the full language. 
 And the more people write code in their own personal (or group) 
dialect, the more fragmented the worldwide codebase becomes, and the 
harder it is to understand code that doesn't come from the circle of 
developers who you're directly familiar with.
I don't totally understand what you're getting at here, but here's my 
take. If people can implement something which can be done using 
metaclasses without using metaclasses then I don't see a problem with 
this. However if someone implements something using metaclasses which 
can be done via other simpler means, then this is a just a education 
problem. It's like the procedural vs functional vs oo programming 
argument all over again. Some people will use OO for everything when it 
may not be best. etc. etc.

It's true that a given programmer doesn't need to understand every 
feature of the language, but it's not really fair to say "ignore it and 
it won't affect you" -- there's still a cost associated with such 
features that can't be ignored away.  In some cases that cost is well 
worth bearing (as is the case for metaclasses and descriptors, 
especially as these two examples are implementation artifacts that would 
exist whether they were exposed to programmers or not), but in other 
cases it won't be, so it's important to keep in mind that the cost exists.
Of course theres a cost with every feature. But with time that costs 
approaches zero if it becomes as rampant as is being suggested because 
you will get use to it. If you see it once every blue moon, well then 
you'll just have to have one very bad day at work.

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


Re: ElementTree, how to get the whole content of a tag

2005-03-16 Thread Damjan
>> Is there any way I could get everything between the  and  tag?
>>
>> 
>>  text
>>  some other text
>>  and then some more
>> 

 gettext(et)
> '\n  text\n  some other text\n  and then some more\n'

I acctually need to get 
'\n  text\n  some other text\n  and then some more\n'

And if there were attributes in  I'd want them too where they were. 
Can't I just get ALL the text between the  tags?

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



Re: Lisp-likeness

2005-03-16 Thread Greg Ewing
Michele Simionato wrote:
However this approach has a drawback (which is not there in Scheme,
since Scheme has set!): if a new scope was created at each iteration
(which is what the function call is doing) we could not reassign
variables (i.e. they would become names locals to the "for" scope,
touching them would not affect variables outside the scope).
There is a middle way: the for-loop could be made
to create a new binding for its control variable
on each iteration, while the body continues to
execute in the outer scope as before.
It would actually be very easy to implement this
in CPython the way it currently works. Guido seems
to be against this sort of thing, though, as he
seems to regard it as a useful feature that the
for-loop control variable is not local to the
loop.
--
Greg Ewing, Computer Science Dept,
University of Canterbury,   
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: code for Computer Language Shootout

2005-03-16 Thread Jacob Lee
On Wed, 16 Mar 2005 16:45:53 -0800, bearophileHUGS wrote:

> Michael Spencer's version is nice, this is a bit shortened version. The
> main() isn't useful for this very short loop, and you can use shorter
> variable names to make lines shorter (this code isn't much readable,
> it's just for the Shootout, "production quality" code has probably to
> be more readable. Code produced by lot of people of a newsgroup isn't
> the normal code usually produced by a single programmer in a limited
> amount of time).
> I've used file(sys.argv[1]) instead of sys.stdin.
> 

I don't see what advantage having smaller variable names gives you. IIRC,
they measure lines of code in logical rather than physical lines.

> 
> . import string, itertools, sys
> .
> . t = string.maketrans('ACBDGHKMNSRUTWVYacbdghkmnsrutwvy',
> .  'TGVHCDMKNSYAAWBRTGVHCDMKNSYAAWBR')
> .
> . for h,b in itertools.groupby( file(sys.argv[1]), lambda x: x[0] in
> ">;" ):
> . if h:
> . print "".join(b),
> . else:
> . b = "".join(b).translate(t, "\n\r")
> . print "\n".join( b[-i:-i-60:-1] for i in xrange(1, len(b),
> 60) )
> 

I benchmarked this, btw - it ran in the same amount of time as the other
solution. It does have the advantage of being significantly fewer lines of
code; I suppose that itertools.groupby, while unexpected to someone from a
language without such niceties in the standard library =), is a better
solution than duplicating the code (or the function call) to translate,
reverse, and format the string.

> --
> 
> The Python Mandelbrot program seems to produce a wrong image:
> 
> http://shootout.alioth.debian.org/benchmark.php?test=mandelbrot&lang=python&id=0&sort=fullcpu
> 

It's my understanding that they use an automated diff with the outputs. So
presumably it's generating correct output or it would be listed as
"Error". I haven't actually checked this, so who knows.

> --
> 
> This is a shorter and faster version of wordfreq:
> http://shootout.alioth.debian.org/benchmark.php?test=wordfreq&lang=python&id=0&sort=fullcpu
> 
> . import string, sys
> .
> . def main():
> . f = {}
> . t = " "*65+ string.ascii_lowercase+ " "*6+
> string.ascii_lowercase+ " "*133
> .
> . afilerl = file(sys.argv[1]).readlines
> . lines = afilerl(4095)
> . while lines:
> . for line in lines:
> . for w in line.translate(t).split():
> . if w in f: f[w] += 1
> . else: f[w] = 1
> . lines = afilerl(4095)
> .
> . l = sorted( zip(f.itervalues(), f.iterkeys()), reverse=True)
> . print "\n".join("%7s %s" % (f,w) for f,w in l)
> .
> . main()
> 

Cool. I haven't looked at this one, but why don't you test it against
their sample data, diff it to make sure the output is identical, and send
it to their mailing list :-).

> --
> 
> This is my shorter and faster version of Harmonic (I hope the use of
> sum instead of the for is okay for the Shootout rules):
> http://shootout.alioth.debian.org/benchmark.php?test=harmonic&lang=python&id=0&sort=fullcpu
> 
> import sys
> print sum( 1.0/i for i in xrange(1, 1+int(sys.argv[1]) ) )
> 

Yes, the current Python version is an embarrassment. I was already
planning to send in the one-character patch (s/range/xrange/) when
submitting the reverse-complement code. This version is probably more
efficient than an explicit loop, although I doubt the difference is by
much. I suppose an ounce of profiling is worth a pound of speculation...

-- 
Jacob Lee
[EMAIL PROTECTED] | www.nearestneighbor.net

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


delny & qhull installed on Windows?

2005-03-16 Thread Jochen Schmidt
Hi There,
Has anybody managed to install the Python delny package including 
qhull on windows?
I tried and got a linker error back:

C:\Program Files\Microsoft Visual Studio\VC98\BIN\link.exe /DLL 
/nologo /INCREMENTAL:NO /LIBPATH:C:\Python23\libs 
/LIBPATH:C:\Python23\PCBuild qhull.lib /EXPORT:init_qhull 
build\temp.win32-2.3\Release\delaunay/_qhullmodule.obj 
/OUT:build\lib.win32-2.3\delaunay\_qhull.pyd /IMPLIB:build\temp.win32-
2.3\Release\delaunay\_qhull.lib
LINK : fatal error LNK1181: cannot open input file "qhull.lib"
error: command '"C:\Program Files\Microsoft Visual 
Studio\VC98\BIN\link.exe"' failed with exit status 1181

thanks for help, jochen
~~~
Jochen Schmidt
National Institute of Water & Atmospheric Research (NIWA)
PO Box 8602, Riccarton, Christchurch, New Zealand
phone + 64 3 343 8058
fax  +64 3 348 5548
email   [EMAIL PROTECTED]
~~~

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


Re: Python becoming less Lisp-like

2005-03-16 Thread Jeremy Bowers
On Wed, 16 Mar 2005 16:35:57 -0600, Mike Meyer wrote:
> The real problem is that newbies won't know which features are "meta"
> features best left to experts, and which features are ok for everyday
> programmers to use.
> 
> We recently saw a thread (couldn't find it in google groups) where
> some was trying to write decorators that would add a variable to a
> functions local namespace. When they actually stated the problem, it
> was a problem trivially solved by inheriting behavior, and that OO
> solution was what the OP finally adopted. But most of a week got
> wasted chasing a "solution" that should never have been investigated
> in the first place.

This isn't a new problem, and I'm not convinced it even makes it worse.
We (speaking broadly) have had to ask "No, what is it you are trying to
*do*?" for a long time. Whether the 'newbie' is reaching for decorators to
add a variable, trying to use lambdas to print, or trying to use XML-RPC
to make calls to local functions, the newbie who is going to ask "How do I
do this wrong thing?" isn't going to be affected either way by the
addition or removal of metaclasses, or much of anything else.

Is this arguable? Yes, absolutely, and I think none of us have the data
to prove this one way or the other. But a priori it is not obvious that
adding a few more possible mistakes to the already effectively infinite
set of them is necessary going to trap anybody who wasn't going to get
trapped on something else.
-- 
http://mail.python.org/mailman/listinfo/python-list


Obfuscated Python: fun with shadowing builtins

2005-03-16 Thread Michael Hoffman
I was compelled to write this today for some reason.
builtins = """__import__ abs basestring bool callable chr
classmethod cmp compile complex delattr dict dir
divmod enumerate eval execfile file filter
float frozenset getattr globals hasattr hash help hex
id input int isinstance issubclass iter len list
locals long map max
min object oct open ord pow
property range raw_input reduce
reload repr reversed round set setattr
slice sorted staticmethod str
sum super tuple type unichr
unicode vars xrange zip"""
unicode=lambda long:apply(long.split);float=lambda 
int:getattr(__builtins__,unicode(builtins)[15])(unicode(builtins)[int]);staticmethod,long=lambda
 long:float(int(str(1)*int(2))*unicode(builtins).index(long.__name__)), lambda 
staticmethod:unicode(apply(builtins.splitlines)[staticmethod]);int=float(0)(apply(str).join(unicode(builtins)[staticmethod(bool)(long(2*int))][staticmethod(bool)(long(2*int+1))]
 for int in staticmethod(classmethod)(staticmethod(bool)(long(-1)
Enjoy ;)
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: I can do it in sed...

2005-03-16 Thread Damjan
Or, much nicer

> if line[:5]=='start': printing=1

if line.startswith('start'): printing=1

> if line[:3]=='end':  printing=0

if line.endswith('end'):  printing=0

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


Re: Why tuple with one item is no tuple

2005-03-16 Thread James Stroud
On Wednesday 16 March 2005 04:45 pm, Robert Kern wrote:
> > This would be very unambiguous.
>
> Not entirely.
>
> > Then, the purity would manifest itself the naked comma being an empty
> > tuple. Think about the zen of:
> >
> >    ,
>
> Is that a tuple or grit on my monitor?  :-)

OK, OK, I'll give up on the commas. Maybe we should just use dollar signs :?

-- 
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095
--
http://mail.python.org/mailman/listinfo/python-list


Re: I can do it in sed...

2005-03-16 Thread John Machin

Kotlin Sam wrote:
> I have spent so much time using sed and awk that I think that way.
Now,
> when I have to do some Python things, I am having to break out of my
> sed-ness and awk-ness, and it is causing me problems. I'm trying.
Honest!
>
> Here are the two things that I'm trying to do:
>   In sed, I can print every line between ^start to ^end by using
> /^start/,/^end/p. It's quick, easy, and doesn't take much time. Is
there
>   a way to do this easily in Python?
>
>   Also, I frequently use something like s/^[A-Z]/~&/ to pre-pend a
tilde
> or some other string to the beginning of the matched string. I know
how
> to find the matched string, but I don't know how to change the
beginning
> of it while still keeping the matched part.
>
> If I were able to stay in the *nix environment for all my work, I
could
> do it with these tools and the beloved pipe(|), but that isn't my lot
in
> life. I would do it in Perl, but, frankly, it gives me headaches even

> looking at it.

You can get gnu Windows versions of awk sed and most other suchlike
goodies off the net ...

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


Re: I can do it in sed...

2005-03-16 Thread Terry Hancock
On Wednesday 16 March 2005 06:01 pm, Kotlin Sam wrote:
> Here are the two things that I'm trying to do:
>   In sed, I can print every line between ^start to ^end by using 
> /^start/,/^end/p. It's quick, easy, and doesn't take much time. Is there 
>   a way to do this easily in Python?

You mean you have a text file and you want to find all the lines between
a line starting with  "start" and one starting with "end".

REs are not your best method here, just do something like this:

lines = open('myfile', 'r').readlines()
printing = 0
for line in lines:
if line[:5]=='start': printing=1
if line[:3]=='end':  printing=0
if printing: print line

Or something like that.  I'm sure there are cleverer ways, but
that should do what you ask for.

Cheers,
Terry

-- 
--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: Why tuple with one item is no tuple

2005-03-16 Thread Robert Kern
James Stroud wrote:
On Wednesday 16 March 2005 07:22 am, Diez B. Roggisch wrote:
As I said: show me which parentheses to use

I kind of like the comma as a tuple "parentheses"
,1,2,3,
replacing
(1,2,3)
or
1,2,3,
or
1,2,3
or (isn't this is getting out of hand?)
(1,2,3,)
Why not--except of course for backward compatability? Comma is not used for 
anything else in python as far as I know.
[1, 2, 3]
{'a': 0, 'b': 2}
f(x, y)
print foo,
This would be very unambiguous. 
Not entirely.
Then, the purity would manifest itself the naked comma being an empty tuple. 
Think about the zen of:

   ,
Is that a tuple or grit on my monitor?  :-)
--
Robert Kern
[EMAIL PROTECTED]
"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter
--
http://mail.python.org/mailman/listinfo/python-list


I can do it in sed...

2005-03-16 Thread Kotlin Sam
I have spent so much time using sed and awk that I think that way. Now, 
when I have to do some Python things, I am having to break out of my 
sed-ness and awk-ness, and it is causing me problems. I'm trying. Honest!

Here are the two things that I'm trying to do:
	In sed, I can print every line between ^start to ^end by using 
/^start/,/^end/p. It's quick, easy, and doesn't take much time. Is there 
 a way to do this easily in Python?

	Also, I frequently use something like s/^[A-Z]/~&/ to pre-pend a tilde 
or some other string to the beginning of the matched string. I know how 
to find the matched string, but I don't know how to change the beginning 
of it while still keeping the matched part.

If I were able to stay in the *nix environment for all my work, I could 
do it with these tools and the beloved pipe(|), but that isn't my lot in 
life. I would do it in Perl, but, frankly, it gives me headaches even 
looking at it.

Any ideas?
Thanks, Lance
--
http://mail.python.org/mailman/listinfo/python-list


Re: code for Computer Language Shootout

2005-03-16 Thread bearophileHUGS
Michael Spencer's version is nice, this is a bit shortened version. The
main() isn't useful for this very short loop, and you can use shorter
variable names to make lines shorter (this code isn't much readable,
it's just for the Shootout, "production quality" code has probably to
be more readable. Code produced by lot of people of a newsgroup isn't
the normal code usually produced by a single programmer in a limited
amount of time).
I've used file(sys.argv[1]) instead of sys.stdin.


. import string, itertools, sys
.
. t = string.maketrans('ACBDGHKMNSRUTWVYacbdghkmnsrutwvy',
.  'TGVHCDMKNSYAAWBRTGVHCDMKNSYAAWBR')
.
. for h,b in itertools.groupby( file(sys.argv[1]), lambda x: x[0] in
">;" ):
. if h:
. print "".join(b),
. else:
. b = "".join(b).translate(t, "\n\r")
. print "\n".join( b[-i:-i-60:-1] for i in xrange(1, len(b),
60) )

--

The Python Mandelbrot program seems to produce a wrong image:

http://shootout.alioth.debian.org/benchmark.php?test=mandelbrot&lang=python&id=0&sort=fullcpu

--

This is a shorter and faster version of wordfreq:
http://shootout.alioth.debian.org/benchmark.php?test=wordfreq&lang=python&id=0&sort=fullcpu

. import string, sys
.
. def main():
. f = {}
. t = " "*65+ string.ascii_lowercase+ " "*6+
string.ascii_lowercase+ " "*133
.
. afilerl = file(sys.argv[1]).readlines
. lines = afilerl(4095)
. while lines:
. for line in lines:
. for w in line.translate(t).split():
. if w in f: f[w] += 1
. else: f[w] = 1
. lines = afilerl(4095)
.
. l = sorted( zip(f.itervalues(), f.iterkeys()), reverse=True)
. print "\n".join("%7s %s" % (f,w) for f,w in l)
.
. main()

--

This is my shorter and faster version of Harmonic (I hope the use of
sum instead of the for is okay for the Shootout rules):
http://shootout.alioth.debian.org/benchmark.php?test=harmonic&lang=python&id=0&sort=fullcpu

import sys
print sum( 1.0/i for i in xrange(1, 1+int(sys.argv[1]) ) )

Bear hugs,
Bearophile

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


Re: Turning String into Numerical Equation

2005-03-16 Thread Giovanni Bajo
Steven Bethard wrote:

>> In fact, the documentation for eval() could be improved to explain
>> the benefits of setting __builtins__ in the globals.
>
> Well, if you think you're pretty clear on what's happening, a patch is
> always appreciated. =)  I have a feeling that the docs are at least
> partially vague because no one actually wants to advertise the
> restricted execution features[1] since no one can guarantee that
> they're really secure...

>[1] Guido say as much
>http://mail.python.org/pipermail/python-dev/2002-December/031234.html

I am by no means clear. I found out by accident this "feature" of eval and
wondered why it is not explained in the documentation. The link you provided is
a good answer to my question. I understand Guido's concerns, in fact.

Then, I should start my usual rant about how is really sad to send patches to
Python and have them ignored for years (not even an acknowledge). Really sad.
This is why I'm not going to do that again.
-- 
Giovanni Bajo


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


Re: Why tuple with one item is no tuple

2005-03-16 Thread James Stroud
On Wednesday 16 March 2005 07:22 am, Diez B. Roggisch wrote:
> As I said: show me which parentheses to use

I kind of like the comma as a tuple "parentheses"

,1,2,3,

replacing

(1,2,3)
or
1,2,3,
or
1,2,3
or (isn't this is getting out of hand?)
(1,2,3,)

Why not--except of course for backward compatability? Comma is not used for 
anything else in python as far as I know. This would be very unambiguous. 
Then, the purity would manifest itself the naked comma being an empty tuple. 
Think about the zen of:

   ,


James


-- 
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: computing a weighted sum

2005-03-16 Thread John Machin

Fernando Perez wrote:
> [EMAIL PROTECTED] wrote:
>
> > Suppose I have a list of n floats x and a list of n floats w and I
want
> > to compute x[0]*w[0] + .. + x[n-1]*w[n-1].
> >
> > Is there some elegant expression (perhaps using lambda) to have it
done
> > in one statement ? As in :
> >  y = lambda x,w : ...
> >
> > I ask because the way I am doing it now :
> >   y = 0
> >   for i in range(0,n): y += x[i]*w[i]
> >
> > doesn't seem very pythonic :)
> >
> > Thanks,
> > Andrei
> >
>
> import Numeric
> print Numeric.dot(x,w)

Indeed. Horses for courses. Anyway, people who reinvent the wheel often
fall to arguing among themselves whose polygon is the best
approximation to a circle, and forget to reinvent the axle. Wouldn't
happen in this newsgroup, of course :-)

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


Re: code for Computer Language Shootout

2005-03-16 Thread Michael Spencer
Steven Bethard wrote:
Michael Spencer wrote:
def output(seq, linelength = 60):
if seq:
iterseq = iter(seq)
while iterseq:
print "".join(islice(iterseq,linelength))

Worth noting: "while iterseq" only works because for this case, you have 
a list iterator, which provides a __len__ method.  
Thanks! I had noted that the file iterator didn't behave like this, but I hadn't 
 deduced the reason.  Unfortunately, the above construct, while cute, is also 
not terribly speedy.

 >>> print "\n".join(body[-index:-index-linelength:-1]
 ...  for index in xrange(1, len(body), linelength))
is ugly but much faster with an already-existing string
So, my second attempt is:
from itertools import groupby
def revcomp2(input = sys.stdin, linelength = 60):
basetable = string.maketrans('ACBDGHKMNSRUTWVYacbdghkmnsrutwvy',
 'TGVHCDMKNSYAAWBRTGVHCDMKNSYAAWBR')
def record(item):
return item[0] in ">;"
for header, body in groupby(input, record):
body = "".join(body)
if header:
print body,
else:
body = body.translate(basetable, "\n\r")
print "\n".join(body[-index:-index-linelength:-1]
for index in xrange(1, len(body), linelength))
Michael
--
http://mail.python.org/mailman/listinfo/python-list


RE: code for Computer Language Shootout

2005-03-16 Thread Delaney, Timothy C (Timothy)
Jacob Lee wrote:

>>  # alias methods to avoid repeated lookup
>>  join = ''.join

I would actually do the alias here sometimes, but give it a
semantically-useful name ...

nosep_join = ''.join

...

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


Re: Why tuple with one item is no tuple

2005-03-16 Thread Daniel Dittmar
Diez B. Roggisch wrote:
I reread his example and have to admit I'm confused: He complains about
having written his _own_ vector class - and concatenation and addition had
to use both + ?
I've interpreted it as:
If Python had choosen different operators for addition and sequence 
concatenation, I could have implemented them both in my vector class. As 
it is, I have to implement one of them using a non-standard operator.

The examples focus too much on numbers - if we use instead 

("foo")
we would get a iterable yielding ["foo",] or - as string already supports
iteration - ['f', 'o', 'o']. Which one to chose?
What I was hinting at (NOT proposing, I'd hate this) was that integers 
implement the [] operator. 5 [0] would then return 5, for all practical 
purposes, it would look like a tuple. String already implements []. Yes, 
that would lead to really surprising and inconsistent behaviour.

I find this 'creative use of overloading' rather awful. But what the
heck, I find list comprehension rather awful.

Well, the number of operators built into the language is limited - and I
actually prefer to have the possibility to overload these if I want to.
Nobody forces me - I could use
v1.concat(v2)
for two vectors v1, v2 if I wanted to.
My peeve is about having operators added to standard types. This 
increases the chances that using an object the wrong way leads to a 
bogus result, not a runtime error. A more common programming error I 
commit is passing a string where a list ist expected. And then I wonder 
why later operations work on one-character strings.

Operator overloading is certainly an irregular verb:
- I make the usage more intuitive
- Yours may lead to misinterpretation
- He obfuscates
Daniel
--
http://mail.python.org/mailman/listinfo/python-list


COM connection point

2005-03-16 Thread Oy Politics
Hello:

I am building a COM client, with the ability to be called back by events.
The events can arrive independently from the server.  The client method is
called at the right time, so that is working.  However, one parameter is
itself a COM object, and I am having trouble with accessing the properties
of the parameter object.

Here is the output of what I have currently.

-- Python execute --
event! 
event! 
event! 

etc.  Obj is supposed to be my intended parameter.  However, when I try to
access its property, I get the following:

-- Python execute --
pythoncom error: Python error invoking COM method.

Traceback (most recent call last):
  File "C:\PYTHON23\Lib\site-packages\win32com\server\policy.py", line 283,
in _Invoke_
return self._invoke_(dispid, lcid, wFlags, args)
  File "C:\PYTHON23\Lib\site-packages\win32com\server\policy.py", line 288,
in _invoke_
return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, None)
  File "C:\PYTHON23\Lib\site-packages\win32com\server\policy.py", line 581,
in _invokeex_
return func(*args)
  File "E:\otsl\testprojects_folder\pythoncom\pyclihh2.py", line 26, in
OnMyEvent
print "event!", obj, obj.AProp
exceptions.AttributeError: 'PyIDispatch' object has no attribute 'AProp'

"QueryInterface" with the target IID gives the following:

exceptions.TypeError: There is no interface object registered that supports
this IID

"CastTo" gives this error:

exceptions.ValueError: This object can not be cast

Thanks a lot,
-OY




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


Re: Python becoming less Lisp-like

2005-03-16 Thread Mike Meyer
[EMAIL PROTECTED] (Paul Boddie) writes:

> Steven Bethard <[EMAIL PROTECTED]> wrote in message news:<[EMAIL 
> PROTECTED]>...
>> 
>> Certainly descriptors in the "wrong hands" could lead to confusing, 
>> unreadable code.  But Python is a "we're all adults here" language, and 
>> so we have to trust other coders to be responsible.
>
> The problem is as much about social dynamics as it is about
> responsibility. Introduce a cool new feature and there'll always be a
> minority who will use it in every situation, no matter how absurd; the
> problem arises when these unnecessary excursions into absurdity start
> to dominate the code you're using or maintaining.

The real problem is that newbies won't know which features are "meta"
features best left to experts, and which features are ok for everyday
programmers to use.

We recently saw a thread (couldn't find it in google groups) where
some was trying to write decorators that would add a variable to a
functions local namespace. When they actually stated the problem, it
was a problem trivially solved by inheriting behavior, and that OO
solution was what the OP finally adopted. But most of a week got
wasted chasing a "solution" that should never have been investigated
in the first place.

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


Re: ElementTree, how to get the whole content of a tag

2005-03-16 Thread Fredrik Lundh
Damjan <[EMAIL PROTECTED]> wrote:

> Given the folowing XML snippet, I build an ElementTree instance with
> et=ElementTree.fromstring(..). Now et.text returns just '\n  text\n  some
> other text'.
> Is there any way I could get everything between the  and  tag?
>
> 
>  text
>  some other text
>  and then some more
> 

def gettext(elem):
text = elem.text or ""
for subelem in elem:
text = text + gettext(subelem)
if subelem.tail:
text = text + subelem.tail
return text

>>> gettext(et)
'\n  text\n  some other text\n  and then some more\n'

 



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


Re: When is a thread garbage collected?

2005-03-16 Thread "Martin v. Löwis"
Kent Johnson wrote:
If I create and start a thread without keeping a reference to the 
thread, when is the thread garbage collected?
When the last reference to the Thread disappears, which is definitely
after the thread terminates.
(Notice that this sentence uses the word thread twice: once to denote
the operating system schedulable unit, and once to denote the Python
object. Only the Python object is subject to garbage collection; the
operating system schedulable unit is not)
For example with this code:
def genpassenger(num):
for i in range(num):
passenger().start()
class passenger(threading.Thread):
def run:
#do something
will all the passenger threads run to completion, then be GCed?
In this example, you'll get a syntax error, because the syntax
for the run method is wrong. If you correct the example, the
answer to the question you asked literally is "yes", but this
is likely not the question you meant to ask. Instead, it might
be that you meant to ask "... then immediately be GCed?" to
which the answer is "it depends on the body of #do something".
IOW, the Thread object may live much longer than the end of the
thread.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: computing a weighted sum

2005-03-16 Thread Fernando Perez
[EMAIL PROTECTED] wrote:

> Suppose I have a list of n floats x and a list of n floats w and I want
> to compute x[0]*w[0] + .. + x[n-1]*w[n-1].
> 
> Is there some elegant expression (perhaps using lambda) to have it done
> in one statement ? As in :
>  y = lambda x,w : ...
> 
> I ask because the way I am doing it now :
>   y = 0
>   for i in range(0,n): y += x[i]*w[i]
> 
> doesn't seem very pythonic :)
> 
> Thanks,
> Andrei
> 

import Numeric
print Numeric.dot(x,w)

Best,

f

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


Simple XML-to-Python conversion

2005-03-16 Thread [EMAIL PROTECTED]
I've been searching high and low for a way to simply convert a small
XML configuration file to Python data structures.  I came across gnosis
XML tools, but need a built-in option for doing something similar.

My knowledge of DOM and anything beyond simple XML structures is
rudimentary at best.  Is there a simple way to use SAX handlers to pull
attributes and elements into Python lists/dictionaries?

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


ElementTree, how to get the whole content of a tag

2005-03-16 Thread Damjan
Given the folowing XML snippet, I build an ElementTree instance with
et=ElementTree.fromstring(..). Now et.text returns just '\n  text\n  some
other text'. 
Is there any way I could get everything between the  and  tag?


  text
  some other text
  and then some more



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


Re: Listbox fill=BOTH expand=YES (Tkinter)

2005-03-16 Thread Raseliarison nirinA
"Christos TZOTZIOY Georgiou" wrote:
> On Tue, 15 Mar 2005 16:48:17 +0300,
> rumours say that [i] might have written:
>
> >yes, indeed.
>  import Tkconstants
>  'True' and 'YES' in dir(Tkconstants)
> >True
> >
> >thanks Harlin,
>
> I hope you also know that
>
> .>> 'inexistent keyword' and 'YES' in dir(Tkconstants)
>
> is also True...

yeah, known but forgotten.

hmmm ...
let's try :

>>> import Tkconstants
>>> 'YES' in dir(Tkconstants)
True
>>> 'True' in dir(Tkconstants)
False
>>> 'TRUE' in dir(Tkconstants)
True
>>> ('inexistent keyword') in dir(Tkconstants)
False

so
>>> 'TRUE' and 'YES' in dir(Tkconstants)
True
>>> 'inexistent keyword' and 'YES' in dir(Tkconstants)
True

i'll recite 42 times truth tables before going to bed.
however i didn't expect the following:

>>> 'inexistent keyword' or 'YES' in dir(Tkconstants)
'inexistent keyword'
>>> False or 'YES' in dir(Tkconstants)
True

hmmm...

>>> ('inexistent keyword' or 'YES') in dir(Tkconstants)
False
>>> (False or 'YES') in dir(Tkconstants)
True

i'll recite 42 times precedence rules before going to bed.
but now i'm a bit confused by the -in- operator. as:

>>> set(['TRUE','YES']).issubset(set(dir(Tkconstants)))
True

i expected this to be true, but it's not:

>>> set(['TRUE','YES']) in set(dir(Tkconstants))
False

originaly, i'm thinking to short-cut the following,
>>> reduce(lambda t,f: t and f, [i in dir(Tkconstants) for i in
'YES','inexistent keyword'])
False
>>> reduce(lambda t,f: t and f, [i in dir(Tkconstants) for i in
'TRUE','YES'])
True

but that was too short and i miss something!
i do reset my brain somewhere between cell234 and cell241
thanks for reading!

--
nirinA
--


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


Re: Good use for Jython

2005-03-16 Thread Sean Blakey
On 15 Mar 2005 23:54:16 -0800, Mike Wimpe <[EMAIL PROTECTED]> wrote:
> Other than being used to wrap Java classes, what other real use is
> there for Jython being that Python has many other GUI toolkits
> available? Also, these toolkits like Tkinter are so much better for
> client usage (and faster) than Swing, so what would be the advantage
> for using Jython? or Is Jython really just so that Java developers can
> write Java code faster?
> 
> Mike Wimpe
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

I use an embedded Jython interpreter extensively for the business
logic layer of a Servlet/J2ee application. The back end uses,
Hibernate to connect to the database, so Jython's JavaBean
functionality is very useful for me, vastly simplifying and clarifying
my own logic.

As an added bonus, it is vastly easier to debug and redeploy a Jython
script file into a running system than it is to do the same with a
session EJB.

-- 
Sean Blakey
Saint of Mild Amusement, Evil Genius, Big Geek
Python/Java/C++/C(Unix/Windows/Palm/Web) developer
quine = ['print "quine =",quine,"; exec(quine[0])"'] ; exec(quine[0])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiple import of a load of variables

2005-03-16 Thread Jeff Shannon
Torsten Bronger wrote:
HallÃchen!
"Fuzzyman" <[EMAIL PROTECTED]> writes:

[...]
I'm not entirely clear what you are trying to do

The following: "variables.py" looks like this
a = 1
b = 2
Then I have helper_a.py, helper_b.py, and helper_c.py which begin
with
from variables import *
And finally, my_module.py starts with
from variables import *
from helper_a.py import *
from helper_c.py import *
from helper_c.py import *
Now imagine that variables.py contained not only two but hundreds of
variables.  Is this then still the most effective approach?
Ugh.  I really don't like the 'from module import *' approach in any 
case, but here, you're binding each name from variables.py at least 
seven times.  Now, it's not like binding names is all *that* 
expensive, but still... I'd call this a code smell.

You say that users of my_module.py may need direct access to these 
variables; to do that well, it does make some sense that my_module 
should import * from variables.  However, I doubt there's any good 
justification for importing the helper modules that way, nor for 
importing * from variables in each of the helper modules.

If you use normal imports in those cases, then once variables.py has 
been loaded into sys.modules (i.e. imported for the first time), you 
create n+3 name bindings as opposed to the 7*n bindings your method is 
creating, where n is the number of names in variables.py.  (The '+6' 
is the 'variables' name in each of the helper modules.)

More importantly, you get clearer code that's easier to maintain and 
troubleshoot.  This fact is far more important than the cost of 
creating name bindings, or any other form of 'efficiency' that is 
likely to apply.  As far as I'm concerned, if you're just going to 
'import *' your helper modules, you might as well leave the whole mess 
as one big file, because you're throwing away almost all of the 
benefits of dividing it into modules.

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


Re: iterable terminology (for language lawyers)

2005-03-16 Thread Raymond Hettinger
[R. Hettinger]
> > You're best bet is to quote the tutorial's glossary,
> > http://docs.python.org/tut/node18.html :

[Michele Simionato]
> Aha! That glossary looks like a nice new addition to the tutorial.
> Maybe the standard library and the language
> reference should link to it somewhere? (maybe
> there already such links but I missed them).

You know where to submit a patch ;-)


> Would you agree with Leif's definition that iterable is
> any x such that iter(x) does not raise an error?

Sure, that is an accurate but not especially informative tautology.

A person can memorize that definition and still know nothing useful like what
they do (return their elements one at a time), what they look like (__iter__ or
__getitem__ methods), or how they work.

You might also mention that monglable is defined as any x such that mongle(x)
does not fail.  Knowing that fact is the key to a complete and deep
understanding of monglation ;-)



Raymond Hettinger


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


Re: getting data with proper encoding to the finish

2005-03-16 Thread John Machin
Ksenia Marasanova wrote:
> John, Serge, thanks for your help!

Thank *you* for having interesting problems :-)

>
> utf-16le  encoding didn't help. I had however to solve it yesterday,
> so I used csv module to create CSV file and then import it in Excel.
> Excel still had troubles with accented characters, but this is
another
> story: it seems that Office 2004 Excel (for Mac, but I assume the PC
> version is no better) cannot import UTF-8 encoded text files.
Encoding
> CSV file with Latin1 encoding finally did work.

Yes, Excel appears not to understand UTF-8. It interprets CSV files
according to the current locale / codepage / whatever -- the "old bad
way" that Unicode is meant to save us from.

An alternative, if you need to represent more than one codepage, or
want a "new good way" of doing it: Excel allows "Save As" to "Unicode
Text" format. It uses Unicode tab u'\t' as delimiter. It quotes tabs,
quotes quotes by doubling them, and [weirdly] also quotes cells which
have only a comma [maybe locale-dependent] in them. It quite happily
opens such files without data loss. You should be able to make such
files easily with Python.

Here's a dump of such a file created by Excel 2002 on Windows -- pls
pardon any Cyrillic spelling errors :-)

>>> file('C:/junk/km_u16.txt', 'rb').read().decode('utf16')
u'\u041c\u0430\u0440\u0430\u0441\u0430\u043d\u043e\u0432\u0430\t\u041a\u0441\u0435\u043d\u044f\r\n"comma,
comma, comma"\t\r\n"quote ""Hello UniWorld""
unquote"\t\r\n"tab\ttab"\t\r\n'

>>> print file('C:/junk/km_u16.txt', 'rb').read().decode('utf16')
ÐÐÑÐÑÐÐÑÐÐÑ

"comma, comma, comma"

"quote ""Hello UniWorld"" unquote"

"tabtab"

To make such a file, you would need a quoter function something like
this; you would apply it to each field:

>>> def unitextquoter(s, quote=u'"', alt_delim=u','):
!   if quote in s:
!   return quote + s.replace(quote, quote+quote) + quote
!   if alt_delim in s or u'\t' in s:
!   return quote + s + quote
!   return s

>>> unitextquoter(u'comma, comma, comma')
u'"comma, comma, comma"'
>>> unitextquoter(u'tab\ttab')
u'"tab\ttab"'
>>> unitextquoter(u'quote "Hello UniWorld" unquote')
u'"quote ""Hello UniWorld"" unquote"'
>>>

Then you would do u'\t'.join(fields) , add on u'\r\n' [or whatever is
needed in your environment], .encode('utf16') and .write() to your 'wb'
file.

>
> Now back to the Excel story, I also think that there is something
> wrong with pyExcelWriter or the way I use it. CSV file generation was
> okay, so I think there is nothing wrong with my data,  or XML parser.
>
> I will resume in a few days with pyExcelWriter and will post the
> results here, but anyway, many thanks for your time and explanation!

I've been reading the source and looking at the Excel file specs
[available from openoffice.org if you're very short of reading
material!]. Apparently pyXLWriter doesn't handle Unicode at all.
Although Unicode came in with Excel 1997 (BIFF8 format file),
pyXLWriter appears to support only Excel 5(?) (BIFF5 format file). As
Serge suggested, appeal to the porter to appeal to the author of the
Perl module it's ported from; but don't hold your breath in the
meantime.

Cheers,
John

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


Re: importerror all 3rd party modules

2005-03-16 Thread John Machin

nyiann wrote:
> Hi,
>
> Brand new to python.  I am trying to install the py2exe modeule, and
when
> I run scripts (simple ones I've made, and examples) I get an
importerror.
> At the python command line I type:
> import py2exe
> and get: 'ImportError: no module named py2exe

Aside: py2exe is used for packaging up Python fully-tested
production-ready scripts so that they can be run as stand-alone
executables in environments where the BOsFH won't let you install
Python. You don't *need* py2exe to run a Python script. It is *not* a
"compiler"; it doesn't make your script run faster. As you are "brand
new to Python", you may want to postpone your investigation of py2exe
for a little while.

>
> So installed everything on my laptop (windows me) and it all works
fine.

It's nice to know that it "works fine" on your laptop. However
palantirs exist only in the story-books; so that we can help you with
the platform on which it *doesn't* work, could you possibly divulge:
which version of Windows, which version of Python, what "trying to
install" means, what example/script you were trying to run, what the
import error was [copy/paste], ...

> Has anyone seen this before?  Am I importing the module incorrectly?
Are
> there platform specifics issues when installing 3rd party modules?

If any, they would be typically be mentioned in the documentation for
the module. Typically, the module's setup.py would handle this.

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


Re: Python becoming less Lisp-like

2005-03-16 Thread Jeff Shannon
news.sydney.pipenetworks.com wrote:
More in relation to the original topic, why can't people just ignore 
features they don't understand and may never use directly. 
Because they may get stuck maintaining code that uses those features. 
 Now, I'm generally in agreement with you -- in general, Python 
features that aren't straightforward (e.g. metaclasses) are clearly 
advanced features and aren't likely to be in everyday code.  I'm okay 
with just knowing that metaclasses exist, and having a vague idea of 
how one would use them.

But the more features that some people ignore, the more that they tend 
to write in a customized dialect that's a subset of the full language. 
 And the more people write code in their own personal (or group) 
dialect, the more fragmented the worldwide codebase becomes, and the 
harder it is to understand code that doesn't come from the circle of 
developers who you're directly familiar with.

It's true that a given programmer doesn't need to understand every 
feature of the language, but it's not really fair to say "ignore it 
and it won't affect you" -- there's still a cost associated with such 
features that can't be ignored away.  In some cases that cost is well 
worth bearing (as is the case for metaclasses and descriptors, 
especially as these two examples are implementation artifacts that 
would exist whether they were exposed to programmers or not), but in 
other cases it won't be, so it's important to keep in mind that the 
cost exists.

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


Re: Writing C readable bitfield structs?

2005-03-16 Thread phark52

Roy Smith wrote:
> In article <[EMAIL PROTECTED]>,
> Cappy2112 <[EMAIL PROTECTED]> wrote:
> >there is a bitfiled mainpulator class inthe Cookbook, but I don't
> >understand his explanation, and the example given doesn't really
show
> >off the features of the class.
>
> I assume you're talking about the struct module?  If you give an
> example of the C struct you're trying to read/write, I could come up
> with some sample code to do it.

struct S {
unsigned int a : 1;
unsigned int b : 1;
unsigned int c : 1;
unsigned int d : 1;
};

fread(from file (file written by Python app) into an instance of struct
S)
then I want it to be used as follows:
if (instance.a) f();
if (instance.b) g();
struct S comes out to 4 on my arch. I do not want to use a new int for
every member of struct S.

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


Re: code for Computer Language Shootout

2005-03-16 Thread Steven Bethard
Michael Spencer wrote:
def output(seq, linelength = 60):
if seq:
iterseq = iter(seq)
while iterseq:
print "".join(islice(iterseq,linelength))
Worth noting: "while iterseq" only works because for this case, you have 
a list iterator, which provides a __len__ method.  This approach will 
not work when you have an iterator that does not provide a __len__ 
method.  For a nice infinite printing loop, try:

def gen():
yield '+'*100
yield '*'*100
output(gen())
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Jython Phone Interview Advice

2005-03-16 Thread George Jempty
Jeremy Bowers wrote:
> On Tue, 15 Mar 2005 03:21:19 -0800, George Jempty wrote:
> > I'm noticing that Javascript's array/"hash" literal syntax is
EXACTLY the
> > same as that for Python lists/dictionaries.
>
> No it isn't, quite.
>
> Two differences of note, one literally syntax and one technically not
but
> you probably still want to know about it.
>
> First, Javascript objects can only use strings for keys, anything
used as
> a key will be converted to a string. Try this in your browser and
you'll
> see what I mean... the "instance" of the "class" I define (let's not
get
> into prototyping issues here :-) ) has its string value used as the
key,
> not the object:

Perhaps the above assertion applies to native Javascript objects only?!
 Because I've been successful in using host(browser) objects as keys to
associative arrays, namely forms.  This is handy when the form's id
and/or name attribute have not been set.  I was concerned that
identical forms would be equal, but then I proved that was not the case
with the following test:






This results in false.  Am cross-posting the rest of this message in
it's entirety to comp.lang.javascript.

> javascript:function a(){}; a.prototype.toString = function () {return
> 'q';}; b = new a(); c = {}; c[b] = 1; alert(c['q'])
>
> (All one line, if your browser objects to the newline.)
>
> The other is the syntax point: The strings you use in {} expressions
to
> denote keys are used literally, they are not resolved. Thus, in the
above
> I *had* to write
>
> c = {};
> c[b] = 1;
>
> Because had I written
>
> c = {b: 1}
>
> I would have ended up with an object where c['b'] == 1; Javascript
does
> not resolve the "expression", 'cause it isn't one.
>
> (That said, certain reserved words like "class" and such do have to
be
> quoted, which means the safe bet is to quote them all, which leads to
> Javascript objects that look identical to Python dicts. But
> 
> {1+2: "moo"}
> 
> will end up different in each language.}

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


Re: __getitem__ method on (meta)classes

2005-03-16 Thread Steven Bethard
Ron Garret wrote:
Using a metaclass allows you to distinguish Fred the plumber from Fred 
the electrician.  But that may or may not be what one actually wants.
Not sure what you mean here.  The non metaclass solution still has 
separate enum.item objects for each new enum.  Consider your implementation:

py> def enum(vals):
... class enum(object):
... class __metaclass__(type):
... def __getitem__(self, index):
... return self.vals[index]
... def __init__(self, val):
... try:
... self.val = type(self).vals.index(val)
... except:
...raise TypeError('%s is not a valid %s' %
...(val, type(self).__name__))
... enum.vals = vals
... return enum
...
py> plumbers = enum(['Fred','John','Bill'])
py> electricians = enum(['Fred','Jake','Lester'])
py> plumbers[0] == electricians[0]
True
py> plumbers('Fred') == electricians('Fred')
False
py> plumbers[0], electricians[0]
('Fred', 'Fred')
py> plumbers('Fred'), electricians('Fred')
(<__main__.enum object at 0x0115D530>, <__main__.enum object at 0x01162D50>)
Note that your implementation conflates plumbers[0] and electricians[0] 
(because your __getitem__ returns the string, not an enum object).  Not 
sure if this is the intended behavior, but it seems a little weird to 
me.  OTOH, plumbers('Fred') and electricians('Fred') are not conflated.

Now consider my implementation:
py> class enum(object):
... class item(object):
... def __init__(self, val):
... self.val = val
... def __init__(self, vals):
... self.items = [type(self).item(val) for val in vals]
... self._val_item_map = dict(zip(vals, self.items))
... def __call__(self, val):
... try:
... return self._val_item_map[val]
... except KeyError:
... raise TypeError('%s is not a valid %s'
... (val, type(self)))
... def __getitem__(self, index):
... return self.items[index]
... def __iter__(self):
... return iter(self.items)
...
py> plumbers = enum(['Fred','John','Bill'])
py> electricians = enum(['Fred','Jake','Lester'])
py> plumbers[0] == electricians[0]
False
py> plumbers('Fred') == electricians('Fred')
False
py> plumbers[0], electricians[0]
(<__main__.item object at 0x011627F0>, <__main__.item object at 0x011883B0>)
py> plumbers('Fred'), electricians('Fred')
(<__main__.item object at 0x011627F0>, <__main__.item object at 0x011883B0>)
Note that Fred the plumber and Fred the electrician always compare as 
inequal (using either __call__ or __getitem__).  Isn't this "allowing 
you to distinguish Fred the plumber from Fred the electrician"?

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


Re: Good use for Jython

2005-03-16 Thread Kent Johnson
Mike Wimpe wrote:
Other than being used to wrap Java classes, what other real use is
there for Jython being that Python has many other GUI toolkits
available? Also, these toolkits like Tkinter are so much better for
client usage (and faster) than Swing, so what would be the advantage
for using Jython? or Is Jython really just so that Java developers can
write Java code faster?
I use Jython a lot. I have a background in Java and I am working in a Java shop, but I prefer to 
code in Python, so Jython has some appeal:
- Works with existing Java libraries, both in-house proprietary libs and favorite third-party libs. 
The third-party libs probably have Python equivalents, but it's nice to be able to keep using some 
favorite tools.
- Doesn't add any new requirements to the target machine (just needs the JRE they already have, 
Python install not needed) (yes, I know about py2exe)
- No one has to know :-) I can ship a jar file (or several) that contains my program, it looks just 
like Java.

A recent poster on jython-users had switched from Python to Jython because he preferred Swing over 
the GUI toolkits available with Python so I guess there is room for more than one opinion on that point.

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


replace from end of string?

2005-03-16 Thread Brian van den Broek
Hi all,
in writing my response to Mark Leeds' recent question about replacing 
text at the end of a string, I was moved to wonder if it wouldn't it 
be handy if the replace method of string instances did one of the 
following:

took a negative integer for count and interpreted that as replace the 
absolute value of count many instance, but starting from the end of 
the string, or,

had a default parameter from_end=False, such that if it were True, 
replacements happened count many times, starting from the end?

I get that it isn't too much of a hassle to write a function to do 
this (heck, *I* did it, so it cannot be too rough ;-). But, it seems a 
common enough task to be a useful addition nevertheless. (And the 
speed of the C implementation wouldn't hurt, either.)

Is there already a pre-rolled way to do this that I've overlooked? Or 
some strong reason there oughtn't be?

Thanks, and best to all,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie: modifying a string in python

2005-03-16 Thread Charles Hartman
You're right that the code you give will not have the desired effect, because strings (unlike lists) are immutable. But slicing comes to your rescue:
for s in stks:
s = s.strip()
if s[-2:] == 'GR':
s = s[:-2] + 'GF'
-- though I'm sure more experienced people will offer more efficient solutions.

Charles Hartman
Professor of English, Poet in Residence
http://cherry.conncoll.edu/cohar
http://villex.blogspot.com

 want to modify a string in the following way :
for s in stks:
  s = s.strip()
  if ( s[-2:] == ‘GR’ ):
  s[-2:]= ‘GF’
 
so, if the last two characters are GR, I want to change
them to GF ( there will be other if statements also but I am
just putting this one here for simplicity ).
 
I think the code is fine but I vaguely remember
reading somewhere in the documentation that
python strings can’t be changed ( only elements of lists can be ) ?.
Is that true or is it okay to do the above.
-- 
http://mail.python.org/mailman/listinfo/python-list

newbie : modifying a string in python

2005-03-16 Thread Leeds, Mark








I want to modify a string in the following way :

 

for s in stks:

  s = s.strip()

  if ( s[-2:] == ‘GR’
):

 
s[-2:]= ‘GF’

 

so, if the last two characters are GR, I want to change

them to GF ( there will be other if statements also but I am

just putting this one here for simplicity ).

 

I think the code is fine but I vaguely remember

reading somewhere in the documentation that

python strings can’t be changed ( only elements of
lists can be ) ?.

Is that true or is it okay to do the above.

.

  
thanks






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

Re: _conditionally_ returning to point where exception was raised?

2005-03-16 Thread Skip Montanaro

>> ... The calling method detects the exception, but needs to get input
>> from the user before deciding whether A.CalledMethod() should
>> continue being executed or permantently stop/cancel the execution of
>> the remaining code in A.CalledMethod(). Can this be done?

Bengt> Once an exception is raised, the stack gets unwound to the point
Bengt> where the exception is caught, so there is no way[1] to recover
Bengt> the context required to "continue" (and eventually "return
Bengt> normally" as if the exception hadn't happened).

I suspect in the OP's case if A.CalledMethod hasn't gone too far before
encountering an IOError it's quite reasonable to thing that B.CallingMethod
just call A.CalledMethod again if it decides to continue.

I will point out that someone posted some "autoload" code here awhile ago
(who was it?) to try to import missing modules.  I use a variant in my
Python startup file:

% python
Python 2.5a0 (#75, Mar 15 2005, 21:55:51) 
[GCC 3.3 20030304 (Apple Computer, Inc. build 1671)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print sin(5)
found sin in math module
-0.958924274663
>>> conn = MySQLdb.Connection
autoloading MySQLdb
>>> conn


After finding the module that needs to be imported, it reexecutes the code
object for the frame where the exception was raised:

exec import_stmt in f_locals, f_globals
exec tb.tb_frame.f_code in f_locals, f_globals

That's not exactly what the OP asked for (it executes the code object from
the beginning, not from the point where the exception was raised with
possibly modified locals and globals), but might provide people with some
ideas.  The full autoload module is at

http://manatee.mojam.com/~skip/python/autoload.py

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


Re: newbie : modifying a string in python

2005-03-16 Thread Brian van den Broek
Leeds, Mark said unto the world upon 2005-03-16 14:46:
I want to modify a string in the following way :
 

for s in stks:
  s = s.strip()
  if ( s[-2:] == 'GR' ):
  s[-2:]= 'GF'
 

so, if the last two characters are GR, I want to change
them to GF ( there will be other if statements also but I am
just putting this one here for simplicity ).
 

I think the code is fine but I vaguely remember
reading somewhere in the documentation that
python strings can't be changed ( only elements of lists can be ) ?.
Is that true or is it okay to do the above.
.
   thanks
Hi Mark,
well, what happens when you try?
>>> test_string = 'some text ending in GR'
>>> if test_string[-2:] == 'GR':
... test_string[-2:] = 'GF'
...
Traceback (most recent call last):
  File "", line 2, in ?
TypeError: object doesn't support slice assignment
So, not so much :-)
You can do it thusly:
>>> if test_string[-2:] == 'GR':
... test_string = test_string[:-2] + 'GF'
...
>>> test_string
'some text ending in GF'
But, a better way in that it uses .endswith and points towards 
generalization:

>>> old_chars = 'GR'
>>> new_chars = 'GF'
>>> test_string = 'some text ending in GR'
>>> if test_string.endswith(old_chars):
... test_string = test_string[:-len(old_chars)] + new_chars
...
>>> test_string
'some text ending in GF'
>>>
Wrap that in a function:
def replace_at_end(string, old, new):
# logic here with a return of the new string as the last line
and you've got something reusable :-)
(There may be better ways, still; I'm no expert :-)
HTH,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: Turning String into Numerical Equation

2005-03-16 Thread Michael Spencer
Giovanni Bajo wrote:
Michael Spencer wrote:

In fact, I believe my solution to be totally safe,
That's a bold claim!  I'll readily concede that I can't access
func_globals from restricted mode eval (others may know better).  But
your interpreter is still be vulnerable to DOS-style attack from
rogue calculations or quasi-infinite loops.

Yes, but I don't see your manually-rolled-up expression calculator being
DOS-safe. I believe DOS attacks to be a problem whenever you want to calculate
the result of an expression taken from the outside. What I was trying to show
is that my simple one-liner is no worse than a multi-page full-blown expression
parser and interpreter.
Fair point that brevity is itself valuable in achieving security.  It isn't 
worth using my "manually-rolled-up expression calculator" simply to deny access 
to func_globals as you have demonstrated.

However, the advantage of the MRUEP is that every operation is evaluated 
individually.  In the example I showed, loops are disabled, attribute access is 
disabled.  Numeric inputs and intermediate results can be checked easily for 
boundedness (though they are not in the example I gave).  This sort of 
fine-grain control is very much harder to do with a straight eval model.

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


Re: Writing C readable bitfield structs?

2005-03-16 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
Cappy2112 <[EMAIL PROTECTED]> wrote:
>there is a bitfiled mainpulator class inthe Cookbook, but I don't
>understand his explanation, and the example given doesn't really show
>off the features of the class.

I assume you're talking about the struct module?  If you give an
example of the C struct you're trying to read/write, I could come up
with some sample code to do it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing C readable bitfield structs?

2005-03-16 Thread Cappy2112
there is a bitfiled mainpulator class inthe Cookbook, but I don't
understand his explanation, and the example given doesn't really show
off the features of the class.

I too need bit-level manipulation, and will probably have to write my
own class to do it.

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


When is a thread garbage collected?

2005-03-16 Thread Kent Johnson
If I create and start a thread without keeping a reference to the thread, when is the thread garbage 
collected?

What I would like is for the thread to run to completion, then be GCed. I can't find anything in the 
docs that specifies this behavior; nor can I think of any other behaviour that seems reasonable :-)

For example with this code:
def genpassenger(num):
for i in range(num):
passenger().start()
class passenger(threading.Thread):
def run:
#do something
will all the passenger threads run to completion, then be GCed?
Thanks,
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: _conditionally_ returning to point where exception was raised?

2005-03-16 Thread Bengt Richter
On 16 Mar 2005 09:53:11 -0800, "MackS" <[EMAIL PROTECTED]> wrote:

>Hi
>
>I'm new to Python and would like to know if the following is possible.
>
>Say I have one lower-level object A and one user-interface object B.
>Suppose B.CallingMethod() calls A.CalledMethod(), the latter method
>stumbles upon an IO error and raises an exception. The calling method
>detects the exception, but needs to get input from the user before
>deciding whether A.CalledMethod() should continue being executed or
>permantently stop/cancel the execution of the remaining code in
>A.CalledMethod(). Can this be done?
>
>What I would like to know is if the calling method is allowed to
>"decide" (at run-time) whether or not the execution of the called
>method resumes. Until now I only see two possibilities: either the
>caller is coded in a way that it handles the exception and execution of
>the called method resumes at the point where the exception was raised
>or the caller was written in a way that doesn't handle it and the
>program is stopped by the interpreter. Is there a third way, ie is it
>possible to determine at run-time whether the called method is resumed?
>
>Thanks in advance,
>
Once an exception is raised, the stack gets unwound to the point where
the exception is caught, so there is no way[1] to recover the context required
to "continue" (and eventually "return normally" as if the exception hadn't 
happened).

One way to preserve the stack is to call a call-back function instead of raising
an exception. Then the call-back could return some information (e.g. user 
input) to
the problem context to make decisions as to how to continue (or not), or the 
callback
itself could also raise an exception.

But then the caller has to be able to provide a call-back function one way or 
another.
If you are designing the whole thing, you can do it, but if you are calling low 
level
services that you can't change, and which raise exceptions, then you may have 
some
fancy wrapping to do to create your desired interface, if it is even possible.

[1] Just to note that I know it is not wise to say "no way" on c.l.py, since 
you never
know what clever people will come up with ;-) Maybe someone will create a way 
for an
exception to return a continuation object of some kind, that could optionally 
be called
from the exception handler to effect as-if return to the point of an exception 
and
continuation from there as if the exception hadn't happened (except maybe some 
updated
binding in the local context that could be seen by the continuing code, and be 
set via
the contination-object call). I have a hunch it's possible, but pretty hairy.

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


Re: _conditionally_ returning to point where exception was raised?

2005-03-16 Thread infidel
There's no "Resume Next" in python.  Once you catch an exception, the
only way you can go is forward from that point.

So if B.CallingMethod catches an exception that was raised in
A.CalledMethod, all it could do is try calling A.CalledMethod again, it
can't jump back to the point where the exception was raised.  About the
best you could, I think, would be to break A.CalledMethod up into
smaller function and let B.CallingMethod call each one in sequence,
deciding whether or not to continue if an exception is raised in any of
them.

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


Access denied calling FireEvent in Python

2005-03-16 Thread calfdog
Hello,

Does anyone know a workaround for calling fireEvent.
With the latest from Microsoft OS XP2 and Hot fixes to
IE it now gives an "access denied" error in Python when called.

Here is what I am trying to do:
Set the "campus" listbox value and theb call fire event, such as in the
code below.  I get an "access denied" error.

example code:
ie = DispatchEx('InternetExplorer.Application')

# Some code to navigate to the site, wait till doc is not busy and #
ReadyState is complete...blah..blah...

ie.Document.forms[0].campus.value = '200'
ie.Document.forms[0].campus.fireEvent('onchange')

HTML code:

Select a campus
Norman Campus
Advanced Programs
Liberal Studies
Academic Programs (CAFE)
OU Tulsa


If you call:
fireEvent('onchange')
fireEvent('onclick')
fireEvent('onFocus') etc... You will get an Access Denied

This only happens with either the newer version of IE and XP2.
I was able to call the exact same code with XP1 and Win2000 Pro
and it work fine. So something has changed with I.E. and is not being
handled in Python.


example code:
ie.Document.forms[0].campus.fireEvent('onchange')

Trace:
 File
"C:\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
line 310, in RunScript
exec codeObject in __main__.__dict__
  File "C:\QA\Tools\cPAMIE150\oCScript2.py", line 24, in ?
ie2.Document.forms[0].campus.fireEvent('onchange')
  File "C:\Python23\Lib\site-packages\win32com\client\dynamic.py", line
165, in __call__
return
self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
com_error: (-2147024891, 'Access is denied.', None, None)

Help would be much appreciated!!

RLM

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


Re: compiled open source Windows lisp (was Re: Python becoming less Lisp-like)

2005-03-16 Thread Brandon J. Van Every
Carl Shapiro wrote:
> "Brandon J. Van Every" <[EMAIL PROTECTED]>
> writes:
>
>> Last I looked, 2 years ago?, there were no compiled, open source
>> lisps that ran on Windows.  Has this changed?
>
> I have a virtually completed port of CMUCL to Win32.  [etc]

Ah, so you're the brave lad I heard about.  :-)  Well, good going!  Hope to
see it sometime.

-- 
Cheers, www.indiegamedesign.com
Brandon Van Every   Seattle, WA

When no one else sells courage, supply and demand take hold.

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


importerror all 3rd party modules

2005-03-16 Thread nyiann
Hi,
Brand new to python.  I am trying to install the py2exe modeule, and when 
I run scripts (simple ones I've made, and examples) I get an importerror. 
At the python command line I type:
import py2exe
and get: 'ImportError: no module named py2exe

So installed everything on my laptop (windows me) and it all works fine.
Has anyone seen this before?  Am I importing the module incorrectly?  Are 
there platform specifics issues when installing 3rd party modules?

Any suggestions appreciated,
N
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python becoming less Lisp-like

2005-03-16 Thread Kay Schluehr
Torsten Bronger wrote:
> Hallöchen!

Moin!

> [First, I wanted to say "descriptors" instead of "decorators" (I
> superseded my post).]
>
> The goal is to trigger function calls when attributes are accessed.
> This is called properties in C# (and maybe in Ruby, too).  Python
> now also has this concept.  What I find ugly is that it is not a
> syntax element.  It looks artificially added to the language.  In
> C#, the "set" and "get" methods form with its attribute a syntactic
> unity.  Everything is together, and no "property" function is
> necessary.

Some people refused properties in Python for exactly this reason.
Defining somewhat like:

def _get_X(self):
return self._X

def _set_X(self,X):
self._X = X

X = property(_get_X, _set_X )

in a Java-style fashion is indeed awfull and clumsy and that people
dismiss such boilerplate code is understandable.

But "Thinking in Java" in Python is probably no good idea allthough
this style can be found in Guidos property-examples presented in his
famous introduction on new-style classes as well:

http://www.python.org/2.2/descrintro.html

I thought for a long time that C# solved this problem with a superior
accurate and compact notion, but paying more attention to the
property() function itself and not to the declarative style getters and
setters opened me a more generic road to reason about desciptors:

def accessor(name, check=None, types=[]):
'''
Generic property creator.
'''
name  = "__"+name
def get(obj):
if not hasattr(obj,name):
setattr(obj,name, None)
return getattr(obj,name)

def set(obj,value):
if types:
if not True in [isinstance(value,t) for t in types]:
raise TypeError, "Can't assign %s to property
%s."%(value,name[2:])
if check:
if not check(value):
   raise TypeError, "Can't assign %s to property
%s."%(value,name[2:])
else:
setattr(obj,name,value)
return property(get,set,None)



Now an example:


class X(object):
a = accessor("a")
b = accessor("b", types = (tuple,list))
c = accessor("c", check = lambda x:hasattr(x,"__len__"))

a,b,c are indeed properties of X !

>>> x = X()
>>> x.b = [1,2,3] # o.k
>>> x.b
[1, 2, 3]
>>> x.b = 0  # raises a TypeError, because a tuple/list is expected
.
.


Regards Kay

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


Re: code for Computer Language Shootout

2005-03-16 Thread Michael Spencer
F. Petitjean wrote:
Le Tue, 15 Mar 2005 23:21:02 -0800, Michael Spencer a écrit :

def output(seq, linelength = 60):
if seq:
iterseq = iter(seq)
while iterseq:
print "".join(islice(iterseq,linelength))
I suppose you mean :
   print "".join( str(item) for item in islice(iterseq, linelength) )
   #  using python 2.4 genexp
No, as written, given the seq is a sequence of single character strings already 
(changing the signature might clarify that):

def output(charseq, linelength = 60):
if charseq:
iterseq = iter(charseq)
while iterseq:
print "".join(islice(iterseq,linelength))
 >>> output("*" * 120, 40)
 
 
 
 >>> output(['*'] * 120, 40)
 
 
 
 >>>
Cheers
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] Who Knows of a Good Computational Physics Textbook?

2005-03-16 Thread Dan Sommers

Thank you beliavsky, Sean, and Scott for the pointers.

Regards,
Dan

-- 
Dan Sommers

Îâ à Îâ à c = 1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: will it cause any problems to open a read-only file & not close it?

2005-03-16 Thread Jeff Shannon
Tim Roberts wrote:
Sara Khalatbari <[EMAIL PROTECTED]> wrote:

Dear friends
In a code, I'm opening a file to read. Like :
  lines = open(filename).readlines()
& I'm never closing it.
I'm not writing in that file, I just read it.
Will it cause any problems if you open a file to read
& never close it?
A file is closed when the last reference to it is deleted.  Since you never
save a reference to this file, the last reference is deleted as soon as the
readlines() call finishes.
So, the file will be closed when you move to the next statement.
This is true in current versions of CPython, but is not necessarily 
true in all implementations of Python.  In particular, Jython uses 
Java's garbage collector; an object becomes available for collection 
when the last reference is deleted, but that collection may not 
(probably won't) happen right away.  Since the automatic file closing 
happens as part of the object deletion, files opened in this way won't 
 be closed until the garbage collector runs (and collects this file 
object).

Most of the time, this won't be a problem, but it's good to be aware 
that things are not necessarily as cut-and-dried as they might seem.

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


_conditionally_ returning to point where exception was raised?

2005-03-16 Thread MackS
Hi

I'm new to Python and would like to know if the following is possible.

Say I have one lower-level object A and one user-interface object B.
Suppose B.CallingMethod() calls A.CalledMethod(), the latter method
stumbles upon an IO error and raises an exception. The calling method
detects the exception, but needs to get input from the user before
deciding whether A.CalledMethod() should continue being executed or
permantently stop/cancel the execution of the remaining code in
A.CalledMethod(). Can this be done?

What I would like to know is if the calling method is allowed to
"decide" (at run-time) whether or not the execution of the called
method resumes. Until now I only see two possibilities: either the
caller is coded in a way that it handles the exception and execution of
the called method resumes at the point where the exception was raised
or the caller was written in a way that doesn't handle it and the
program is stopped by the interpreter. Is there a third way, ie is it
possible to determine at run-time whether the called method is resumed?

Thanks in advance,

Mack Stevenson

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


Re: Writing C readable bitfield structs?

2005-03-16 Thread Larry Bates
[EMAIL PROTECTED] wrote:
> How would I go about writing a bitfield that can be read by my C app? I
> want to pack a few bools into one int.
> 
> I know an extended module exists (npstruct) which helps you do this but
> I want to do it manually or using one of the standard modules.
> 
struct.pack is in the Standard Library and allows you to do what
you want.  You may find that you must also do some "bit twiddling"
using << shift functions and | bit or function if you want to pack
tighter than on 4 bit boundaries.

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


Re: __getitem__ method on (meta)classes

2005-03-16 Thread Ron Garret
In article <[EMAIL PROTECTED]>,
 Steven Bethard <[EMAIL PROTECTED]> wrote:

> Ron Garret wrote:
> > In article <[EMAIL PROTECTED]>,
> >  Steven Bethard <[EMAIL PROTECTED]> wrote:
> > 
> >>>Yeah, except I actually left out one thing:  I also want type(v)==e1.
> >>
> >>Why?  In Python usually you rely on duck-typing and not explicit type 
> >>checks.  What is it that you're trying to gain by asserting type(v) == e1?
> > 
> > Clarity.  I want to be able to distinguish a member of an enumeration 
> > from a string or an integer for the same reason one would want to 
> > distinguish 123 from "123".
> 
> So then you don't necessarily need that type(v) == e1, you just need 
> type(v) != str.  How about:

[xnip]

That's not bad.  This conflates all enumerated items into a single 
namespace whereas the metaclass solution makes each enumeration its own 
namespace.  For example:

plumbers = enum['Fred','John','Bill']
electricians = enum['Fred','Jake','Lester']

Using a metaclass allows you to distinguish Fred the plumber from Fred 
the electrician.  But that may or may not be what one actually wants.

Must sleep on it.

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


Re: Mark attribute as read-only

2005-03-16 Thread Steven Bethard
Florian Lindner wrote:
how can I mark a attribute of a class as read-only (for non classmembers)?
Yes, stupid question, but the docu gave me no help.
Declare it as such in the documentation. ;)
If you want to provide error messages, you could alternatively define a 
property:

py> class C(object):
... def _getx(self):
... return self._x
... x = property(fget=_getx)
... def __init__(self, x):
... self._x = x
...
py> c = C(4)
py> c.x
4
py> c.x = 6
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: can't set attribute
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Minidom empty script element bug

2005-03-16 Thread Derek Basch
Cross post from XML-SIG:

--- Walter Dörwald <[EMAIL PROTECTED]> wrote:
> Martin v. Löwis sagte:
> > Derek Basch wrote:
> > >[...]
> >> How do I get minidom to NOT render an empty script element? Should
I
> submit a bug report?
> >
> > That said, I think there is a simple solution: add an empty Text
node to
> the script element:
> >
> > script_node_0.appendChild(doc.createText(u""))
> >
> > [Disclaimer: this is untested; from reading the source, I think it
should
> work]
>
> If this doesn't work, you might want to try XIST
> (http://www.livinglogic.de/Python/xist)
> instead of minidom. XIST knows that the script element is not EMPTY,
and when
> the
> output is in HTML compatible XML an end tag will be produced:
>
> >> from ll.xist.ns import html
> >>> print html.script(type="text/javascript",
> src="../test.js").asBytes(xhtml=1)
> 
>
> Using pure XML mode gives:
>
> >>> print html.script(type="text/javascript",
> src="../test.js").asBytes(xhtml=2)
> 
>
> Bye,
>Walter Dörwald

Wow! XIST is very elegant. Perfectly designed for what it is supposed
to do.

"XIST is an extensible HTML/XML generator written in Python."

I guess there isn't much point in "fixing" the pyXML XHTMLPrinter when
something as cool as XIST exists (pun intended).

Kid also seems really neat. I like the TAL like features. However, it
seems less mature than XIST.

There seems to be lots of functionality crossover between the two but
it is good that there is enough demand for XML output functionality in
python to support two distinct modules.

Thanks Everyone!,
Derek Basch

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


How to add a shapefile to an existing ArcMap 9.x project using Python?

2005-03-16 Thread syed_saqib_ali
Hi.


I have an Instance of ArcMap 9.0 running.


I also have a shapefile named myShape (actually corresponding to 4
files on the disk: myShape.dbf, myShape.shp, myShape.pnt and
myShape.shx)


I would like to write some Python code that inserts myShape into the
running instance of ArcMap9.0 as a new layer.


How can I do this? What software tools/package can I use to do this?
Can you show me the Python code fragment? 


Thanks 
-Saqib

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


Re: computing a weighted sum

2005-03-16 Thread andreif
Even if language permits
  sum(x*w for x, w in zip(x, w))
would seem confusing for anyone watching the code

Maybe
   sum(xi*wi for xi, wi in zip(x, w)) 
would be more appropiate

Andrei

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


[OT] Re: Python becoming less Lisp-like

2005-03-16 Thread Brian van den Broek
news.sydney.pipenetworks.com said unto the world upon 2005-03-16 05:57:

trust the guy to do a good job. If you don't, then you can write it 
yourself which means you can do exactly how you want it which again 
makes the whole argument mute.
Anyone else having images of mimes engaged in street fights? ;-)
Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Mark attribute as read-only

2005-03-16 Thread Florian Lindner
Hello,
how can I mark a attribute of a class as read-only (for non classmembers)?
Yes, stupid question, but the docu gave me no help.

Thanks,

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


Writing C readable bitfield structs?

2005-03-16 Thread phark52
How would I go about writing a bitfield that can be read by my C app? I
want to pack a few bools into one int.

I know an extended module exists (npstruct) which helps you do this but
I want to do it manually or using one of the standard modules.

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


Re: Why tuple with one item is no tuple

2005-03-16 Thread Diez B. Roggisch
> I think he meant that Python should have introduced different operators
> for addition and sequence concatenation.

I reread his example and have to admit I'm confused: He complains about
having written his _own_ vector class - and concatenation and addition had
to use both + ?

He could have used | for concatenation instead. Apart from the concatenation
IMHO not being a mathematical founded operation on vectors.

I maybe was confused of him using + as bad example and then extending that
to *. But even more so my point is valid: If you forbid the overloading of
operators, you have to come up with even _more_ operator names, like ocaml
has *. and * for multiplication of floats and ints. So you end up with way
more clutter in the source, certainly more than the occasional extra comma.

>> Your opinion is wrong. It's because you seem to not have understood the
>> example: The expression (5 + 4) could be understood as 9 or as (9,). In
> 
> It should be understood as 9, but if integers etc implement the sequence
> protocol, 9 can be used just like a tuple
> (http://www.livejournal.com/users/glyf/29038.html).

The examples focus too much on numbers - if we use instead 

("foo")

we would get a iterable yielding ["foo",] or - as string already supports
iteration - ['f', 'o', 'o']. Which one to chose?

> 
> There have been other proposals where you could write 'for i in 5' etc.
> 
> I find this 'creative use of overloading' rather awful. But what the
> heck, I find list comprehension rather awful.

Well, the number of operators built into the language is limited - and I
actually prefer to have the possibility to overload these if I want to.
Nobody forces me - I could use

v1.concat(v2)

for two vectors v1, v2 if I wanted to.


-- 
Regards,

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


Re: Why tuple with one item is no tuple

2005-03-16 Thread Steven Bethard
Daniel Dittmar wrote:
But what the heck, I find list comprehension rather awful.
Sacrilege! ;)
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: computing a weighted sum

2005-03-16 Thread Steven Bethard
Will McGugan wrote:
In Python 2.3
sum( [ _x * _w for _x, _w in zip( x, w ) ] )
or in 2.4
sum( _x * _w for _x, _w in zip( x, w ) )
Any reason for the leading underscores?  If you're trying to avoid 
polluting your namespace, you should note that generator expressions 
don't leak their loop variables, so you can write the second as:

sum(x*w for x, w in zip(x, w))
without any worries of overwriting x and w.  (Of course I would probably 
name them something different anyway, e.g. x_item and w_item...)

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


Re: Getting current variable name

2005-03-16 Thread Steven Bethard
pl wrote:
I followed the mails entitled 'How to turn a variable name into a
string?' in march 2005 posts as I have a similar problem.
I have to get some list variable names at some point in my program. So
I ended up looking into globals() to get them with a small function like
this:
#!/usr/bin/python
l1 = ['r', 'r', 't']
l2 = ['r', 't', 't']
l3 = ['t', 't', 't']# Two equivalent lists but...
l4 = ['t', 't', 't']# with different names
def nameofObj(obj):
#   print locals()
globdict = globals()
var = globals().keys()
for i in var :
if globdict[i] == obj:
print i
print '-'*20 ,'\n'
nameofObj(l1)
print '-'*20 ,'\n'
map(nameofObj, [l1, l2, l3, l4])
What is the problem you're trying to solve here?  Looking up the names 
of an object is not usually something you want to do.  If you provide a 
little more detail on your use case, we might be able to help you 
refactor this code.

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


Re: Why tuple with one item is no tuple

2005-03-16 Thread Daniel Dittmar
Diez B. Roggisch wrote:
for instance I have written once somekind of vector class where
it was natural for these vectors to be added as well as te be
concatenated. Unfortunately python uses "+" for both so I had
no way to have both operators in a natural way in python.

And no way in mathematics or any other language either - if you want the
same function symbol on the same operators to have _different_ semantics,
you're getting pretty non-deterministic.
I think he meant that Python should have introduced different operators 
for addition and sequence concatenation.

Your opinion is wrong. It's because you seem to not have understood the
example: The expression (5 + 4) could be understood as 9 or as (9,). In
It should be understood as 9, but if integers etc implement the sequence 
protocol, 9 can be used just like a tuple 
(http://www.livejournal.com/users/glyf/29038.html).

There have been other proposals where you could write 'for i in 5' etc.
I find this 'creative use of overloading' rather awful. But what the 
heck, I find list comprehension rather awful.

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


Re: computing a weighted sum

2005-03-16 Thread TZOTZIOY
On 16 Mar 2005 06:49:09 -0800, rumours say that [EMAIL PROTECTED] might have
written:

>Suppose I have a list of n floats x and a list of n floats w and I want
>to compute x[0]*w[0] + .. + x[n-1]*w[n-1].
>
>Is there some elegant expression (perhaps using lambda) to have it done
>in one statement ? As in :
> y = lambda x,w : ...
>
>I ask because the way I am doing it now :
>  y = 0
>  for i in range(0,n): y += x[i]*w[i]
>
>doesn't seem very pythonic :)

Your method seems to be the one closest to what's generally considered as
pythonic.

Anyway, a functional equivalent:

.>> from itertools import starmap, izip
.>> import operator
.>> x= [1,2,3,4]
.>> w=[3.0, 6.0, 9.0, 12.0]
.>> sum(starmap(operator.mul, izip(x,w)))
90.0
.>>
-- 
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Turning String into Numerical Equation

2005-03-16 Thread Steven Bethard
Giovanni Bajo wrote:
In fact, the documentation for eval() could be improved to explain the benefits
of setting __builtins__ in the globals.
Well, if you think you're pretty clear on what's happening, a patch is 
always appreciated. =)  I have a feeling that the docs are at least 
partially vague because no one actually wants to advertise the 
restricted execution features[1] since no one can guarantee that they're 
really secure...

STeVe
[1] Guido say as much 
http://mail.python.org/pipermail/python-dev/2002-December/031234.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: computing a weighted sum

2005-03-16 Thread andreif
Thanks Will, the 2.4 expression looks really nice.

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


Re: Good use for Jython

2005-03-16 Thread Tom Willis
On 15 Mar 2005 23:54:16 -0800, Mike Wimpe <[EMAIL PROTECTED]> wrote:
> Other than being used to wrap Java classes, what other real use is
> there for Jython being that Python has many other GUI toolkits
> available? Also, these toolkits like Tkinter are so much better for
> client usage (and faster) than Swing, so what would be the advantage
> for using Jython? or Is Jython really just so that Java developers can
> write Java code faster?
> 
> Mike Wimpe
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

I haven't done anything substatial with Jython yet, but I consder it
to be valuable in areas where you have to do something quick and
dirty, perhaps debug an EJB running on an app server for example.

Bean shell serves the same purpose and the syntax is pretty much Java
so the learning curve isn't as steep for java developers.

I see it as a way of getting around some of the requirements of the
language. If I needed to connect to java systems together and I needed
to do it quickly, and the quality of requirements was less than
adequate, I'd rather write a script(beanshell/jython/groovy) than
booting up eclipse and contributing to the interface cesspool .

-- 
Thomas G. Willis
http://paperbackmusic.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why tuple with one item is no tuple

2005-03-16 Thread Diez B. Roggisch
> That ambiguity is only caused because python uses the same characters
> for very different operations and to be honest I don't like that.

As I said: show me which parentheses to use - and keep in mind that:

 - < and > are for comparisions and the same ambiguity troubles arise 
 - unicode surely features some usable characters (e.g. the quotation markes
that look like <<, but are one char). But for one that complains that
typing and additional comma is too much already, I doubt that having to
press some weird multi key stroke is a viable option. To me neither, as I
prefer my parentheses to be accessed easily, even on a vi running in a
console from a tn3270 terminal


> 
> for instance I have written once somekind of vector class where
> it was natural for these vectors to be added as well as te be
> concatenated. Unfortunately python uses "+" for both so I had
> no way to have both operators in a natural way in python.

And no way in mathematics or any other language either - if you want the
same function symbol on the same operators to have _different_ semantics,
you're getting pretty non-deterministic.


> 
> So that a <*> would create an ambiguity if items would be silently
> transformed in a one-item tuple when appropiate is IMO more caused
> by the design decision to use <*> for two totally diffent operations
> then because of the dynamic nature of python.

Your opinion is wrong. It's because you seem to not have understood the
example: The expression (5 + 4) could be understood as 9 or as (9,). In
python (and each and every other dynamically typed language) you can't
decide which version to take. So you have to decide on _one_, and as every
kid in school learns that (5+4) * 5 is 45, it was a reasonable decision to
use the semantics we have today.

In a statically typed language, (5+4) _could_ be the tuple if the expression
is used in a typing context that makes that determinable. An example would
be

list((5+4))

as the list constructor needs a iterable to work, so it would be declared
like this:

list _ : [ iterable[alpha] ] -> list[alpha]

But then you'd have to forbid overloading of operators, or someone could
declare a list like this:

list _ : [ num ] -> list[int]

to create lists of zeros of type int. Which would reintroduce the ambiguity
again.


>> And if the static typed language allows operator overloading, it could
>> very well be that someone creates a overloading for
>>
>><*> : [tuple[num], tuple[num]] -> 
>>
>> which would reintroduce the ambiguity.
>>
>> Soo, in the end it boils down to some explicitness - where IMHO an
>> additional comma is pretty much no problem at all. Another option would
>> of course be the introduction of different parentheses for tuples - but I
>> can't find some on my keyboard.
> 
> Well I can't find braille on my keyboard, but if I wanted to, it
> wouldn't be difficult to get it on my screen. So is it with
> different parentheses. That python can't use these parentheses
> is again a design decision.

For someone who expresses his disliking to type _one_ comma in the few cases
of single element tuples in thousands of lines of code, it strikes me odd
that you'd go an are willing to add extra trouble entering _each_ and
_every_ tuple in your code by using some hitherto unknown character that
won't be enterable easily 

But you showed that strange sense of reasoning before - I remember you
wanting to shave off microseconds by optimising constant expressions like
5*4 whilst at the same time arguing in another thread that you'd like to
have mutable keys for dicts that needed copying the very same keys - at
much greater costs, per case and even more so in general as using dicts is
common where pure constant arithmetic expressions aren't.


-- 
Regards,

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


  1   2   >