Re: slicing the end of a string in a list

2006-03-02 Thread Peter Otten
John Salerno wrote:

> You can probably tell what I'm doing. Read a list of lines from a file,
> and then I want to slice off the '\n' character from each line.

If you are not concerned about memory consumption there is also

open(filename).read().splitlines()

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


Re: slicing the end of a string in a list

2006-03-02 Thread Leif K-Brooks
Ben Cartwright wrote:
> No, since the line variable is unused.  This:
> 
>   i = 0
>   for line in switches:
>   line = switches[i][:-1]
>   i += 1
> 
> Would be better written as:
> 
>   for i in range(len(switches)):
>   switches[i] = switches[i][:-1]

This is better, IMHO:

for i, switch in enumerate(switches):
 switches[i] = switch[:-1]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RPC client class?

2006-03-02 Thread Fredrik Lundh
Dick Watson wrote:

> We have a legacy device that exposes an RPC server. We have an RPCL
> defininition of its interface. We want to develop an RPC client of this
> interface in Python that will be usable in both Win32 and open systems
> environments.
>
> I can find some *very* dated references to a demo/rpc.py

if the RPC you're talking about is Sun RPC, the whole concept is pretty
dated (the original RFCs are from the late eighties).

> but I can't find such a file on my Win Python install.

it's in the source distribution, which is browsable via svn.python.org:

http://svn.python.org/view/python/trunk/Demo/rpc

if you have a subversion client, you can get a local copy with

svn co http://svn.python.org/projects/python/trunk/Demo/rpc

otherwise, you can grab the entire source archive from:

http://python.org/download/

hope this helps!





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


Re: Write a GUI for a python script?

2006-03-02 Thread [EMAIL PROTECTED]
Grant Edwards wrote:
> On 2006-03-02, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> > Note that wxWindows wraps native widgets,
>
> Not on Linux/KDE systems.  ;)

Right, I followed that with a clarification of supported systems.  You
can use wxwindows with gtk-qt to get a Qt-ish look, although that's not
ideal.

The issue with wxqt is licensing; wxWindows is open-source, but not GPL
(it allows closed-source app development); gtk is LGPL'd so that's not
an issue, but Qt is GPL'd.  Julian Smart (wxwindows developer)
contacted Troll for license clarifications but didn't get a response
(or not a useful one, I can't remember the specifics).  There's no
ideological opposition to a qt implementation if the licensing can be
resolved (indeed they're willing to work with fully closed-source
toolkits, they just don't want to force application developers using
their toolkit to use a particular license).

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


Re: newbie question

2006-03-02 Thread Tim Roberts
Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:

>On 1 Mar 2006 12:47:26 -0800, "D" <[EMAIL PROTECTED]> declaimed the
>following in comp.lang.python:
>
>> Yep, that should work.  Just keep in mind that if python.exe is not in
>> your path, you will need to either specify the entire path to it
>> (i.e. 'C:\python24\python C:\path\to\script\myscript.py'), or cd into
>> its directory first (i.e. if you want to just run 'python
>> C:\path\to\script\myscript.py').
>> 
>   Actually, on XP at least, some combination of commands enables
>things such that one can run without the "python" or the ".py" (but I
>think it garbages I/O redirection and maybe command line arguments --
>though this one worked)

That's the PATHEXT environment variable.

  C:\tmp>set PATHEXT
  PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.PY;.PYW;.tcl

If you give a lone file name without an extension, it will try all of those
extensions, in that order, to find an executable.  Just add .PY to the end.

There is a bug in NT's CMD.EXE that screws up redirection of stdin, but
command line arguments and stdout work just fine.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


help in converting perl re to python re

2006-03-02 Thread eight02645999
hi

i have some regular exp code in perl that i want to convert to python.


if $line =~ m#<(tag1)>(.*)#
   {
 $variable = $2;
}

the perl code finds a line that matches something like

"sometext<\tag1>" in the line and then assign $variable the value
of  "sometext"

how can i do an equivalent of that using re module?
thanks

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


Qns on blank lines

2006-03-02 Thread eight02645999
hi

i have some regular exp code in perl that i want to convert to python.


if $line =~ m#<(tag1)>(.*)#
   {
 $variable = $2;
}

the perl code finds a line that matches something like

"sometext<\tag1>" in the line and then assign $variable the value
of  "sometext"

how can i do an equivalent of that using re module?
thanks

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


Re: how to overload sqrt in a module?

2006-03-02 Thread Michael McNeil Forbes
> On Thu, 2 Mar 2006 16:12:53 -0800, Michael McNeil Forbes wrote:
>
>> I would like to write a module that provides some mathematical functions
>> on top of those defined in math, cmath etc. but I would like to make it
>> work with "any" type that overloads the math functions.
>>
On Fri, 3 Mar 2006, Dennis Lee Bieber wrote:
>   Since Python doesn't dispatch based on parameter types, there are
> only two choices that I can see...
>
>   Either the CALLER already knows what the arguments are, and has
> coded an explicit call to the version of the function desired...

The caller does know in my case, but wants to reuse old code that performs 
a complicated computation using the standard math functions.  I was 
thinking that maybe there was some way for the caller to pass the 
appropriate functions to the module on import, but could not find a way of 
doing this.

>   OR, the caller imports and calls your special module, and your
> special module has to import ALL possible override modules and supply a
> function that determines which of the modules is to be used...

This is essentially what numpy.sqrt() etc. does as pointed out by Robert 
Kern.  The numpy.sqrt() seems to check if the argument is real, complex, 
or some other type and calls either math.sqrt, cmath.sqrt or x.sqrt() 
appropriately.  This works for my problem: I just wondered if there was a 
more generic solution without having to do this work.

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


Re: how to overload sqrt in a module?

2006-03-02 Thread Michael McNeil Forbes
>> Are there any other more generic solutions (without having to write
>> "custom" functions like numpy.sqrt)?
>
> No. *Someone* always has to write those "custom" functions. In the case of 
> len()
> and abs(), that someone was Guido. For numpy.sqrt(), that someone was Travis
> Oliphant. For anything else you want, that someone is probably you.

Thanks Guido!  Thanks Travis:-)

What I was thinking was: is there some way to pass a parameter to the 
module on import so that the module can then use the correct environment.

If I could pass a dictionary to the module with all of the overloaded 
functions, then they could become part of the module's environment and 
used appropriately.  I could not find a way of passing such a dictionary.

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


Re: Importing Files

2006-03-02 Thread Terry Hancock
On Thu, 2 Mar 2006 21:40:44 -0800 (PST)
anushya beauty <[EMAIL PROTECTED]> wrote:
>   I am new to this python. I have installed python 2.4
>   in my windows xp system. 
>   
>   My issue is:
>   i have three directories with some files. 
>   ex: Dir ---> Dir1 / file1.1.py
>  "   ---> Dir2 / file2.1.py
>  "   ---> Dir3 / file3.1.py
>   These are the example directories i have. (Under
>   Dir--->Dir1, Dir2  and Dir3; Under Dir1 --->file1.1.py;
>   Dir2 ---> file2.1.py; Dir3  > file3.1.py)  In
>   file3.1.py, i am importing the file1.1.py and file2.1.py
>   using the command:  from file1.1 import *
>   from file2.1 import  *
>   
>   Now, my problem is, file1.1 is imported and i can access
>   the values  that are used in that file. But the file2.1
>   is not imported and  returning the error message as
>   "ImportError: No module named file2.1".  I couldn't
>   access the var used in that file. Actually, both the
>   files  are from different directories only. Then, why
>   onr file is imported and  another is not imported?.

First of all, do not use "." in module names, even in
examples. The "." is an operator in python, so it's really
confusing to read -- "import file.1" if interpreted
literally, is nonsense. At least I hope it is.

>   My Question is: How to import the files from the
>   different directory to the current file?.

Typically you will need to modify sys.path to determine
what's on the "PYTHONPATH".

Of course, you can also modify the PYTHONPATH environment
variable to add new stuff to the path.

Cheers,
Terry

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

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


Re: how to overload sqrt in a module?

2006-03-02 Thread Robert Kern
Michael McNeil Forbes wrote:

> Are there any other more generic solutions (without having to write 
> "custom" functions like numpy.sqrt)?

No. *Someone* always has to write those "custom" functions. In the case of len()
and abs(), that someone was Guido. For numpy.sqrt(), that someone was Travis
Oliphant. For anything else you want, that someone is probably you.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: slicing the end of a string in a list

2006-03-02 Thread Paul Rubin
John Salerno <[EMAIL PROTECTED]> writes:
> Interesting. So I would say:
> 
> [line.rstrip() for line in open('C:\\switches.txt')]

Yes, you could do that.  Note that it builds up an in-memory list of
all those lines, instead of processing the file one line at a time.
If the file is very large, that might be a problem.

If you use parentheses instead:

  (line.rstrip() for line in open('C:\\switches.txt'))

you get what's called a generator expression that you can loop
through, but that's a bit complicated to explain, it's probably better
to get used to other parts of Python before worrying about that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Importing Files

2006-03-02 Thread anushya beauty
Hi,    I am new to this python. I have installed python 2.4 in my windows xp system. My issue is:  i have three directories with some files.   ex: Dir ---> Dir1 / file1.1.py     "   ---> Dir2 / file2.1.py     "   ---> Dir3 / file3.1.py  These are the example directories i have. (Under Dir--->Dir1, Dir2  and Dir3; Under Dir1 --->file1.1.py; Dir2 ---> file2.1.py; Dir3  > file3.1.py)   In file3.1.py, i am importing the file1.1.py and file2.1.py using the command:   from file1.1 import *  from file2.1 import  *Now, my problem is, file1.1 is imported and i can access the values  that are used in that file. But the file2.1 is not imported and  returning the error message as "ImportError: No module named file2.1".  I couldn't access the var used in that file. Actually, both the files  are !
 from
 different directories only. Then, why onr file is imported and  another is not imported?.My Question is: How to import the files from the different directory to the current file?.Anybody please reply me, i have strucked in this simple file importing concept.Thanks and Regards,  abbi.  
		Relax. Yahoo! Mail 
virus scanning helps detect nasty viruses!-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how to overload sqrt in a module?

2006-03-02 Thread Michael McNeil Forbes
> Michael McNeil Forbes wrote:
>> Here is one fairly ugly solution:
>>
>> module_g.py
>> ---
>> def g(x,math):
>> return math.sqrt(x)
>>
>>
> import math, cmath, module_g
> module_g.g(2,math)
>>
>> 1.4142135623730951
>>
> module_g.g(-2,cmath)
>>
>> 1.4142135623730951j
>>
>> What is the "proper" pythonic way to do this?
>
On Thu, 2 Mar 2006, Robert Kern wrote:
>
> Use the appropriate library which already implements the features you want.
>
> In [8]: class A(object):
>   ...: def __init__(self, x):
>   ...: self.x = x
>   ...: def sqrt(self):
>   ...: return 2*self.x
>   ...:
>   ...:
>
> In [9]: a = A(10)
>
> In [10]: import numpy
>
> In [11]: numpy.sqrt(a)
> Out[11]: 20
>
> In [12]: numpy.sqrt(10)
> Out[12]: 3.1622776601683795
>
> In [13]: numpy.sqrt(10j)
> Out[13]: (2.2360679774997898+2.2360679774997898j)
>
> -- 
> Robert Kern

Thanks.  This solution is essentially to make sure that all "numeric" 
objects have .sqrt etc. members, and then use a library which check 
against builtin types and custom types with these extensions.

That works, as long as the appropriate library exists (or I write it 
myself) (and this works in my case: I did not realize that the numpy/scipy
functions worked this way.)

Are there any other more generic solutions (without having to write 
"custom" functions like numpy.sqrt)?

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


Re: slicing the end of a string in a list

2006-03-02 Thread John Salerno
John Salerno wrote:
> Paul Rubin wrote:
> 
>> The preferred way to remove the newline is more like:
>>for line in open('C:\\switches.txt'):
>>  print line.rstrip()
> 
> Interesting. So I would say:
> 
> [line.rstrip() for line in open('C:\\switches.txt')]

That seems to work. And on a related note, it seems to allow me to end 
my file on the last line, instead of having to add a newline character 
at the end of it so it will get sliced properly too.
-- 
http://mail.python.org/mailman/listinfo/python-list


Swig, Python, and C++

2006-03-02 Thread Mich Peffe
Greetings All,I'm using SWIG for the first time and am running into some problems.  I've tried researching at swig.org and python.org, but unfortunately, most of the examples use programs I don't have, such as Solaris, Unix, and Irix.  I wish to make my C++ classes and functions accessible from Python, and create the glue code necessary to interface with my compiler.  I'm using Python 2.4, MS Visual Studio 2005, and Windows XP command prompt.C++ Code:/* FuncTest.h */#include int fact(int n){    if(n <=1) return 1;    else return n*fact(n-1);}char *get_time(){    time_t ltime;    time(

Re: slicing the end of a string in a list

2006-03-02 Thread John Salerno
Paul Rubin wrote:

> The preferred way to remove the newline is more like:
>for line in open('C:\\switches.txt'):
>  print line.rstrip()

Interesting. So I would say:

[line.rstrip() for line in open('C:\\switches.txt')]
-- 
http://mail.python.org/mailman/listinfo/python-list


Python/Zope Jobs

2006-03-02 Thread OSS
1) Contract/Telecommute Python Crawler Developer
2) Python/C++ Developer, Greenwich, CT | 80-160k | Relo OK
3) Python/Zope Dev, Rockville, MD | 60-100k | Relo OK

See http://groups.yahoo.com/group/pythonzopejobs for each job details


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


Re: in need of some sorting help

2006-03-02 Thread ianaré
arrrg i did it again, not enough explanation... new to asking for
programing help online.
anyway the reason is that the list can be rearanged later in the
program by another function, and i need a way to put it in order
again.. so yes it is doing some pretty funky stuff, lol.
so although your method works well, it would have been problematic for
me to implement a two list system in the app for various reasons. but
you did make me understand  a way to sort this thing finally: sort by
base path then by full path, which is how i came up with:

files.sort(key=lambda x: x.lower())
files.sort(key=lambda x: os.path.dirname(x))

well actually i am sorting first by full name, then by base, taking
advantage of python2.4's stable sort().

If you can think of a more efficient (faster) way of doing this please
let me know. i'm not crazy about having to sort this list twice, it can
get pretty big (50,000 entries)

anyway thanks all, this thing had me stuck for over a month !!

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


RPC client class?

2006-03-02 Thread Dick Watson
We have a legacy device that exposes an RPC server. We have an RPCL 
defininition of its interface. We want to develop an RPC client of this 
interface in Python that will be usable in both Win32 and open systems 
environments.

I can find some *very* dated references to a demo/rpc.py, but I can't find 
such a file on my Win Python install. There is an rpc.py in idle, but it 
doesn't seem to be a general purpose implementation. (I can find **lots** of 
references to xmlrpc.py, but the server predates all of this neato XML 
stuff. I also found the "Stackless" rpc.py; it wants to modify base Python. 
I'd rather not diverge from the stock Python.)

Is there a Python module suitable for RPC client creation? Where? Why is 
this not a standard class? Are we nuts to pursue this course? 


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


Re: do design patterns still apply with Python?

2006-03-02 Thread gene tani

Terry Hancock wrote:
>
> This sounds like an article crying out to be written,
> "(Learning) Design Patterns with Python".
>
> Has it been written already?
>
> Cheers,
> Terry
>
> --
> Terry Hancock ([EMAIL PROTECTED])
> Anansi Spaceworks http://www.AnansiSpaceworks.com

There's a couple Alex M slideshows and a couple discussions of
Creational/Structural / Behavioral patterns

http://www.strakt.com/docs/ep04_pydp.pdf

http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html
http://www.pasteur.fr/formation/infobio/python/ch18s06.html
http://www.sauria.com/~twl/conferences/pycon2005/20050323/Design%20Patterns%20and%20Python%20OOP%20-%20Objects%20By%20Design.html

i think mostly i flip thru the Oreilly cookbook whenever i need
something.

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


Re: when do two names cease to refer to the same string object?

2006-03-02 Thread John Salerno
Farshid Lashkari wrote:
> I asked a similar question a few weeks ago. I think the answers I got 
> will also answer your question as well. Here's a link to the thread:
> 
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/2f6f1d399ba94a7b/f564a219ffe44149?lnk=st&rnum=1&hl=en#f564a219ffe44149
> 
> -Farshid

Thanks! Very interesting stuff. Seems like basically that sometimes 
strings are reused, and sometimes they are created anew. I also 
understand the point about not relying on the implementation, but like 
you I was just curious.  :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: slicing the end of a string in a list

2006-03-02 Thread Paul Rubin
John Salerno <[EMAIL PROTECTED]> writes:
> >   print [line[:-1] for line in open('C:\\switches.txt')]
> 
> Hmm, I just realized in my original code that I didn't escape the
> backslash. Why did it still work properly?

The character the backslash isn't special: \s doesn't get into
a code like \n, so the backslash is passed through.  Best not to
rely on that.

The preferred way to remove the newline is more like:
   for line in open('C:\\switches.txt'):
 print line.rstrip()

the rstrip method removes trailing whitespace, which might be \n
on some systems, \r\n on other systems, etc.

> And do I not need the 'r' parameter in the open function?

No you get 'r' by default.  If you want to write to the file you need
to pass the parameter.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: when do two names cease to refer to the same string object?

2006-03-02 Thread Farshid Lashkari
I asked a similar question a few weeks ago. I think the answers I got 
will also answer your question as well. Here's a link to the thread:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/2f6f1d399ba94a7b/f564a219ffe44149?lnk=st&rnum=1&hl=en#f564a219ffe44149

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


Re: slicing the end of a string in a list

2006-03-02 Thread John Salerno
Ben Cartwright wrote:

>   print [line[:-1] for line in open('C:\\switches.txt')]

Hmm, I just realized in my original code that I didn't escape the 
backslash. Why did it still work properly?

By the way, this whole 'one line' thing has blown me away. I wasn't 
thinking about list comprehensions when I started working on this, but 
just the fact that it can all be done in one line is amazing. I tried 
this in C# and of course I had to create a class first, and open the 
file streams, etc.  :)

And do I not need the 'r' parameter in the open function?
-- 
http://mail.python.org/mailman/listinfo/python-list


Need help in Python Wrapper for EWFAPI from XPe

2006-03-02 Thread P Boy
I am trying to build a wrapper for the EWFAPI running on XPe. My first
attempt was to use SWIG, but run to trouble with all these windows
types such as WCHAR, DWORD, LPWSTR, ...

I then searched further and found out about the ctypes module. However,
some functions returns pointer to struct in ewfapi.dll. How do get into
the elements of struct pointer, recursively, if possible?

Thanks for any help in advance.

Oh, writing a wrapper on top of ewfapi is an option, but it would be
painful and time consuming.

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


Re: how do you move to a new line in your text editor?

2006-03-02 Thread jussij
> One thing I like to do is use tabs for my indentation, because
> this makes it easy to outdent when I need to start a new line
> in column 1. I can press backspace once and move 4 spaces to
> the left.

Zeus has a Smart Backspace feature (configurable on or off) where
by it will try to line up the current line with the lines of code
above on any backspace key press.

This means that in the case you describe a backspace will always
move back 4 spaces whether the white space is made up of tabs
or spaces.

> But I read in the PEP that spaces are recommended over tabs. If
> this is the case, it would involve pressing backspace 4 times (or
> 8, etc.) to get back to column 1.

It only takes one key press if you are using Zeus ;)

Jussi Jumppanen
Author: Zeus for Windows
Zeus for Windows IDE
http://www.zeusedit.com

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


Re: Making a tiny script language using python: I need a string processing lib

2006-03-02 Thread Paul McGuire
"Sullivan WxPyQtKinter" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> I do not know if there is any lib specially designed to process the
> strings in scipt language.
> for example:
> I hope to process the string"print a,b,c,d,e "in the form"command
> argumentlist" and return:
> {'command'='print',
> 'argumentlist'=['a','b','c','d','e']}
> Are there any lib to implement this?
>
>
> Ideally , the lib should have a function like below:
>
> def extract(commandstring, splitformat)
>
> eg:
> extract("[EMAIL PROTECTED]","[EMAIL PROTECTED]")
> return: {"what":"see","whom":"you","when":"tonight"}
>
> extract("1;2;3;4;5","list[;]")
> return: {"list":['1','2','3','4','5']}
>
> extract("print a,b,c,d,e","command arglist[,]")
> return: {"command":"print","arglist":['a','b','c','d','e']}
>
> extract("fruit:apple~orgrange~pear~grape#name:tom;sam;dim;ham"
>  ,"class1:instance1[~]#class2:instance2[;]")
> return: {"class1":"fruit",
>  instance1:['apple','orange','pear','grape'],
>  "class2":"name",
>  "instance2":['tom','sam','dim','ham']
>  }
>
>
>
> ### # # # #
>## #  #   #
>## #   # #
>#####
>## #   # #
>## #  #   #
>## # # #
>
I gave two presentations at PyCon on using pyparsing, one was for a simple
adventure game that implemented a command parser.  You can find the
presentations and sample code at
http://www.geocities.com/ptmcg/python/index.html.

-- Paul


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


Re: slicing the end of a string in a list

2006-03-02 Thread John Salerno
Ben Cartwright wrote:

> Actually, it creates a new string instance with the \n character
> removed, then discards it.  The original switches[0] string hasn't
> changed.
> Yes.  You are repeated assigning a new string instance to "line", which
> is then never referenced again.  

Ah, thank you!

> PS - actually, you can accomplish all of the above in a single line of
> code:
>   print [line[:-1] for line in open('C:\\switches.txt')]

Wow, that just replaced 7 lines of code! So *this* is why Python is 
good.   :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: slicing the end of a string in a list

2006-03-02 Thread Ben Cartwright
John Salerno wrote:
> You can probably tell what I'm doing. Read a list of lines from a file,
> and then I want to slice off the '\n' character from each line. But
> after this code runs, the \n is still there. I thought it might have
> something to do with the fact that strings are immutable, but a test
> such as:
>
> switches[0][:-1]
>
> does slice off the \n character.

Actually, it creates a new string instance with the \n character
removed, then discards it.  The original switches[0] string hasn't
changed.

  >>> foo = 'Hello world!'
  >>> foo[:-1]
  'Hello world'
  >>> foo
  'Hello world!'

> So I guess the problem lies in the
> assignment or somewhere in there.

Yes.  You are repeated assigning a new string instance to "line", which
is then never referenced again.  If you want to update the switches
list, then instead of assigning to "line" inside the loop, you need:

  switches[i] = switches[i][:-1]

> Also, is this the best way to index the list?

No, since the line variable is unused.  This:

  i = 0
  for line in switches:
  line = switches[i][:-1]
  i += 1

Would be better written as:

  for i in range(len(switches)):
  switches[i] = switches[i][:-1]

For most looping scenarios in Python, you shouldn't have to manually
increment a counter variable.

--Ben

PS - actually, you can accomplish all of the above in a single line of
code:
  print [line[:-1] for line in open('C:\\switches.txt')]

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


Re: how to overload sqrt in a module?

2006-03-02 Thread Robert Kern
Michael McNeil Forbes wrote:
> Here is one fairly ugly solution:
> 
> module_g.py
> ---
> def g(x,math):
> return math.sqrt(x)
> 
> 
import math, cmath, module_g
module_g.g(2,math)
> 
> 1.4142135623730951
> 
module_g.g(-2,cmath)
> 
> 1.4142135623730951j
> 
> I am sure there is a better way of doing this that makes use of the 
> type of the argument (Dynamical scoping would solve the 
> problem but we don't want to go there...).  Note that the following 
> function would work fine
> 
> def f(x):
> return abs(x)
> 
> because of the special member __abs__ attached to the type.  There is no 
> corresponding member for sqrt, sin etc.
> 
> What is the "proper" pythonic way to do this?

Use the appropriate library which already implements the features you want.

In [8]: class A(object):
   ...: def __init__(self, x):
   ...: self.x = x
   ...: def sqrt(self):
   ...: return 2*self.x
   ...:
   ...:

In [9]: a = A(10)

In [10]: import numpy

In [11]: numpy.sqrt(a)
Out[11]: 20

In [12]: numpy.sqrt(10)
Out[12]: 3.1622776601683795

In [13]: numpy.sqrt(10j)
Out[13]: (2.2360679774997898+2.2360679774997898j)

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: how to overload sqrt in a module?

2006-03-02 Thread mforbes
>> I would like to write a module that provides some mathematical functions on 
>> top of those defined in math, cmath etc. but I would like to make it work 
>> with "any" type that overloads the math functions.
>> 
>> Thus, I would like to write:
>> 
>> module_f.py
>> 
>> def f(x):
>>""" Compute sqrt of x """
>>return sqrt(x)
>> 
> from math import *
> import module_f
> module_f.f(3)
>> 
>> Traceback (most recent call last):
>>File "", line 1, in ?
>>File "module_f.py", line 2, in f
>>  return sqrt(x)
>> NameError: global name 'sqrt' is not defined
>> 
>> I understand why sqrt is not in scope, but my question is: what is the best 
>> way to do this?
>
> You need to import math in the module that uses it. Imports in one module 
> don't (in general) affect the variables available in another module.
>
> module_f.py
> 
> from math import sqrt # more explicit than from math import *
> def f(x):
>   """ Compute sqrt of x """
>   return sqrt(x)
>
> Kent

I know, but the point is that I want to allow the user of the module to be 
able to specify which sqrt function should be used depending on the type 
of x.  Importing math in the module would prevent the user from using f() 
with complex types (or dimensioned types for another example).

That is why I suggested the ugly, but functional solution

module_g.py
---
def g(x,a_math):
 """Compute sqrt of x using a_math.sqrt)
 return a_math.sqrt(x)

The user can at least specify to use cmath instead of math:

>>> import cmath, module_g
>>> module_g.g(8j,cmath)
(2+2j)

Michael.

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


slicing the end of a string in a list

2006-03-02 Thread John Salerno
Here's the code I wrote:

file = open('C:\switches.txt', 'r')
switches = file.readlines()
i = 0

for line in switches:
line = switches[i][:-1]
i += 1

print switches


You can probably tell what I'm doing. Read a list of lines from a file, 
and then I want to slice off the '\n' character from each line. But 
after this code runs, the \n is still there. I thought it might have 
something to do with the fact that strings are immutable, but a test 
such as:

switches[0][:-1]

does slice off the \n character. So I guess the problem lies in the 
assignment or somewhere in there.

Also, is this the best way to index the list?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do design patterns still apply with Python?

2006-03-02 Thread Paul Rubin
"ajones" <[EMAIL PROTECTED]> writes:
> Design patterns are kind of like sarcasm: hard to use well, not always
> appropriate, and disgustingly bad when applied to problems they are not
> meant to solve.

+1 QOTW
-- 
http://mail.python.org/mailman/listinfo/python-list


Roundup Issue Tracker release 1.1.1

2006-03-02 Thread Richard Jones
I'm proud to release this, the 1.1.1 release of Roundup.

Fixed in this release:

- failure with browsers not sending "Accept-Language" header
  (sf bugs 1429646 and 1435335)
- translate class name in "required property not supplied" error message
  (sf bug 1429669)
- error in link property lookups with numeric-alike key values (sf bug
  1424550)
- ignore UTF-8 BOM in .po files
- add permission filter to menu() implementations (sf bug 1431188)
- lithuanian translation updated by Nerijus Baliunas (sf patch 1411175)
- incompatibility with python2.3 in the mailer module (sf bug 1432602)
- typo in SMTP TLS option name: "MAIL_TLS_CERFILE" (sf bug 1435452)
- email obfuscation code in html templating is more robust
- blank-title subject line handling (sf bug 1442121)
- "All users may only view and edit issues, files and messages they
  create" example in docs (sf bug 1439086)
- saving of queries (sf bug 1436169)
- "Adding a new constrained field to the classic schema" example in docs
  (sf bug 1433118)
- security check in mailgw (sf bug 1442145)
- "clear this message" (sf bug 1429367)
- escape all uses of "schema" in mysql backend (sf bug 1397569)
- date spec wasn't allowing week intervals

If you're upgrading from an older version of Roundup you *must* follow
the "Software Upgrade" guidelines given in the maintenance documentation.

Roundup requires python 2.3 or later for correct operation.

To give Roundup a try, just download (see below), unpack and run::

python demo.py

Release info and download page:
 http://cheeseshop.python.org/pypi/roundup
Source and documentation is available at the website:
 http://roundup.sourceforge.net/
Mailing lists - the place to ask questions:
 http://sourceforge.net/mail/?group_id=31577


About Roundup
=

Roundup is a simple-to-use and -install issue-tracking system with
command-line, web and e-mail interfaces. It is based on the winning design
from Ka-Ping Yee in the Software Carpentry "Track" design competition.

Note: Ping is not responsible for this project. The contact for this
project is [EMAIL PROTECTED]

Roundup manages a number of issues (with flexible properties such as
"description", "priority", and so on) and provides the ability to:

(a) submit new issues,
(b) find and edit existing issues, and
(c) discuss issues with other participants.

The system will facilitate communication among the participants by managing
discussions and notifying interested parties when issues are edited. One of
the major design goals for Roundup that it be simple to get going. Roundup
is therefore usable "out of the box" with any python 2.3+ installation. It
doesn't even need to be "installed" to be operational, though a
disutils-based install script is provided.

It comes with two issue tracker templates (a classic bug/feature tracker and
a minimal skeleton) and five database back-ends (anydbm, sqlite, metakit,
mysql and postgresql).

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


Re: Making a tiny script language using python: I need a string processing lib

2006-03-02 Thread James Stroud
Sullivan WxPyQtKinter wrote:
> I do not know if there is any lib specially designed to process the
> strings in scipt language.
> for example:
> I hope to process the string"print a,b,c,d,e "in the form"command
> argumentlist" and return:
> {'command'='print',
> 'argumentlist'=['a','b','c','d','e']}
> Are there any lib to implement this?
> 
> 
> Ideally , the lib should have a function like below:
> 
> def extract(commandstring, splitformat)
> 
> eg:
> extract("[EMAIL PROTECTED]","[EMAIL PROTECTED]")
> return: {"what":"see","whom":"you","when":"tonight"}
> 
> extract("1;2;3;4;5","list[;]")
> return: {"list":['1','2','3','4','5']}
> 
> extract("print a,b,c,d,e","command arglist[,]")
> return: {"command":"print","arglist":['a','b','c','d','e']}
> 
> extract("fruit:apple~orgrange~pear~grape#name:tom;sam;dim;ham"
>  ,"class1:instance1[~]#class2:instance2[;]")
> return: {"class1":"fruit",
>  instance1:['apple','orange','pear','grape'],
>  "class2":"name",
>  "instance2":['tom','sam','dim','ham']
>  }

Your best bets are simpleparse (http://simpleparse.sourceforge.net/) or 
ply (http://www.dabeaz.com/ply/ply.html). Both have a little learning 
curve but are well worth the time investment if you will be doing things 
like you describe.

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


Re: Question

2006-03-02 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 "Tom Leggio" <[EMAIL PROTECTED]> wrote:

> Do I need this on my computer---Python---can I remove it without hurting 
> anything?
> Thanks Tommy

Tom,

That's a very difficult question to answer without knowing more about your 
computer.  Some systems depend on Python for administrative tasks.  If you 
remove Python on such a system, you could create a mess for yourself.

Why do you want to remove it?  Even if you never use it, it's probably not 
taking up much space and it's not hurting anything.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to overload sqrt in a module?

2006-03-02 Thread Kent Johnson
Michael McNeil Forbes wrote:
> I would like to write a module that provides some mathematical functions 
> on top of those defined in math, cmath etc. but I would like to make it 
> work with "any" type that overloads the math functions.
> 
> Thus, I would like to write:
> 
> module_f.py
> 
> def f(x):
>""" Compute sqrt of x """
>return sqrt(x)
> 
 from math import *
 import module_f
 module_f.f(3)
> 
> Traceback (most recent call last):
>File "", line 1, in ?
>File "module_f.py", line 2, in f
>  return sqrt(x)
> NameError: global name 'sqrt' is not defined
> 
> I understand why sqrt is not in scope, but my question is: what is the 
> best way to do this?

You need to import math in the module that uses it. Imports in one 
module don't (in general) affect the variables available in another module.

module_f.py

from math import sqrt # more explicit than from math import *
def f(x):
""" Compute sqrt of x """
return sqrt(x)

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


Question

2006-03-02 Thread Tom Leggio
Do I need this on my computer---Python---can I remove it without hurting 
anything?
Thanks Tommy

-- 
Please visit my web page @tomleggio.com
Tom Leggio
194 NE 6th. CT.
Dania Beach, Fl 33004-3633
954-205-5307 


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


Making a tiny script language using python: I need a string processing lib

2006-03-02 Thread Sullivan WxPyQtKinter
I do not know if there is any lib specially designed to process the
strings in scipt language.
for example:
I hope to process the string"print a,b,c,d,e "in the form"command
argumentlist" and return:
{'command'='print',
'argumentlist'=['a','b','c','d','e']}
Are there any lib to implement this?


Ideally , the lib should have a function like below:

def extract(commandstring, splitformat)

eg:
extract("[EMAIL PROTECTED]","[EMAIL PROTECTED]")
return: {"what":"see","whom":"you","when":"tonight"}

extract("1;2;3;4;5","list[;]")
return: {"list":['1','2','3','4','5']}

extract("print a,b,c,d,e","command arglist[,]")
return: {"command":"print","arglist":['a','b','c','d','e']}

extract("fruit:apple~orgrange~pear~grape#name:tom;sam;dim;ham"
 ,"class1:instance1[~]#class2:instance2[;]")
return: {"class1":"fruit",
 instance1:['apple','orange','pear','grape'],
 "class2":"name",
 "instance2":['tom','sam','dim','ham']
 }



### # # # #
   ## #  #   #
   ## #   # #
   #####
   ## #   # #
   ## #  #   #
   ## # # #

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


Re: setattr question

2006-03-02 Thread Kent Johnson
Gerard Flanagan wrote:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/86900
> 
> mais il utilise 'apply', qui est...blah
> 
> I was trying to implement the factory pattern.
> The recipe above uses 'apply' which is deprecated according to the
> docs, and I suppose I was curious how to do the same sort of thing
> without 'apply'.

Apply has been replaced by 'extended call syntax', that is why it is 
deprecated. Instead of
 return apply(self._function,_args,_kargs)

write
return self._function(*_args, **_kargs)

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


when do two names cease to refer to the same string object?

2006-03-02 Thread John Salerno
To test this out a wrote a little script as an exercise:

for num in range(1, 10):
x = 'c' * num
y = 'c' * num

if x is y:
   print 'x and y are the same object with', num, 'characters'
else:
   print 'x and y are not the same object at', num, 'characters'
   break

But a few questions arise:

1. As it is above, I get the 'not the same object' message at 2 
characters. But doesn't Python only create one instance of small strings 
and use them in multiple references? Why would a two character string 
not pass the if test?

2. If I say x = y = 'c' * num instead of the above, the if test always 
returns true. Does that mean that when you do a compound assignment like 
that, it's not just setting each variable to the same value, but setting 
them to each other?

Finally, I'd like to see how others might write a script to do this 
exercise. Basically I just wanted to see when two names stop referring 
to the same string, which I figured was based on length of the string. 
But I've also noticed that putting spaces in the string also affects 
things, so maybe there isn't just one way to test this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do design patterns still apply with Python?

2006-03-02 Thread Paul Rubin
Roy Smith <[EMAIL PROTECTED]> writes:
> > Sandboxed code is a real obvious one.
> What is "sandboxed code"?

It's what the old rexec/bastion module tried unsuccessfully to
implement: a way of running potentially hostile code while limiting
the kinds of harmful stuff it can do.  This is needed for things like
browser applets.  Javascript (not related to Java except by name) also
depends on it.  A web browser that let arbitrary web pages run python
scripts would be totally insecure and would let the site implementers
take over your browser.  Obviously not every application needs this,
but it's hard to do unless there's fairly deep support for it in the
language.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do design patterns still apply with Python?

2006-03-02 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Paul Rubin  wrote:

> Roy Smith <[EMAIL PROTECTED]> writes:
> > > Somewhat less often, something is easy in Java and difficult in
> > > Python.
> > Example?
> 
> Sandboxed code is a real obvious one.

What is "sandboxed code"?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do design patterns still apply with Python?

2006-03-02 Thread Paul Rubin
Roy Smith <[EMAIL PROTECTED]> writes:
> > Somewhat less often, something is easy in Java and difficult in
> > Python.
> Example?

Sandboxed code is a real obvious one.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do design patterns still apply with Python?

2006-03-02 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Paul Rubin  wrote:

> Somewhat less often, something is easy in Java and difficult in
> Python.

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


Re: do design patterns still apply with Python?

2006-03-02 Thread Thomas G. Willis
On 3/2/06, Terry Hancock <[EMAIL PROTECTED]> wrote:
On Thu, 02 Mar 2006 16:38:44 -0500Roy Smith <[EMAIL PROTECTED]> wrote:> In article <[EMAIL PROTECTED]
>,>  John Salerno <[EMAIL PROTECTED]> wrote:> > Since Python does so many things different, especially> > compared to  compiled and statically typed languages, do
> > most of the basic design  patterns still apply when> > writing Python code? If I were to read a  design pattern> > book (such as Head First Design Patterns), could I apply> > their Java examples to Python easily enough, or does
> > Python require a  different perspective when applying> > patterns?> [...]> The basic concepts in the pattern books are worth knowing.>  You just have> to be able to tease apart the concepts from the
> language-specific cruft  that so often obfuscates the> descriptions.This sounds like an article crying out to be written,"(Learning) Design Patterns with Python".Has it been written already?
Cheers,TerryBruce Eckel began writing "Thinking In Python" it was last updated in 2001.He's a busy dude with a lot on his plate, so finishing it or updating it isn't known.
I emailed him once about it and actually got a cordial reply which amounted to,..."I have no time but I'd love to finish it" But, the draft does have some interesting tidbits in it and it's worth a look I think. You def. get the message that patterns apply a lot differently in python as compared to the {...;} languages.
Details here.http://mindview.net/Books/Python/ThinkingInPython.html-- Thomas G. Willis---
http://i-see-sound.comhttp://tomwillis.sonicdiscord.comAmerica, still more rights than North Korea
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how do you move to a new line in your text editor?

2006-03-02 Thread Sudden Disruption
John,

> This is a real small point

No point is small when you apply it hundreds of times a day.  I spent
quite a bit of time on this element and ended up allowing conversion
from tabs to spaces and the reverse. Who knows what you'll find in the
world of ASCII.

Historically, Tabs were stops on the typewriter carriage, a control
function.  This Tabs = Spaces thing came about largely because of
cursor bondage.

So how do YOU think of a Tab key?  Is it a data key or a control key?

Internally, I treat Tab (and Shift Tab) as a navigation (control) key
instead of pumping in lots of spaces.  It seems more useful that way.
But then Sudden View doesn't have "cursor bondage" to worry about.

Sudden Disruption

Try Sudden View - for the art of editing text
Beta test now in progress at...
http://www.sudden.net/

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


Re: do design patterns still apply with Python?

2006-03-02 Thread Paul Rubin
John Salerno <[EMAIL PROTECTED]> writes:
> Since Python does so many things different, especially compared to
> compiled and statically typed languages, do most of the basic design
> patterns still apply when writing Python code? If I were to read a
> design pattern book (such as Head First Design Patterns), could I
> apply their Java examples to Python easily enough, or does Python
> require a different perspective when applying patterns?

I'd say the relative importance of particular patterns depends on
whether the problems it solves are easier or harder in the language
you're using.  Many things that are difficult in Java are easy in
Python, so the patterns in the book aren't terribly relevant.
Somewhat less often, something is easy in Java and difficult in
Python.  When that happens, you may need approaches that aren't in the
book.  Finally, you have to think of all of these books as different
approaches of explaining elephants to blind men.  There's a lot of
murkiness in programming and design patterns are yet another way to
help guide people through it.  But the more programming you do, the
better your own internal maps and instincts become, and the less you
need a guidebook that doesn't always correspond to the actual
landscape you're operating in.  So consider the books to contain
helpful guidelines but don't feel afraid to trust your own instincts
over them, especially after those instincts become better developed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with dbi, odbc module and Oracle 9.2 - suffixed "L" with number data type

2006-03-02 Thread Andrew MacIntyre
[posted & mailed]

[EMAIL PROTECTED] wrote:

> The only issue I've had so far is retrieving data from Oracle when an
> integer has been defined like:
> 
>number(p)[same thing as number(p,0) evidently]
> 
> This is from a database I didn't design and can't change. Evidently
> there are new ways to declare integer data types in Oracle.
> 
> The problem is that the ODBC module suffixes an "L" to any integer
> returned that
> was defined as data type number(p). For example, an integer stored as:
> 56  will be returned as 56L. Actually, it now seems to be doing the
> same thing, at least in some cases, for number data types declared as
> number(p,s). What gives? Anyone know why this would happen?

The 'L' suffix indicates a Python long, which is an arbitrary precision
integer.  If you're confident that the number in question is in the
normal integer range, you can coerce it to a normal int with int(p) so
the formatting on display doesn't include the suffix - if the number
is too large to coerce an OverflowError will be raised (for 2.2 and
earlier at least; 2.4 and later unify ints and longs).

> Can't use mxODBC because it's a commercial product and can't use
> cx_oracle at the moment because I am stuck with Python 2.1 (for ESRI
> geoprocessing), and there is no cx_oracle for Python 2.1 (starts with
> Python 2.2 and refuses to install for 2.1). I could install a later
> version of Python independently, but I need to be able to do the
> geoprocessing that 2.1 allows as well as ODBC calls to Oracle all in
> the same script. This means dbi,odbc seems to be my only choice.

If you have access to a compiler, you may be able to build cx_Oracle
for Python 2.1, but you would have to check that the code doesn't 
require  Python 2.2 or later features.  The MingW gcc package should 
work with
Python 2.1 (which was built with VC6 as I recall).

I've been bugging ESRI about upgrading, and I'm sure others have too.

-
Andrew I MacIntyre "These thoughts are mine alone..."
E-mail: [EMAIL PROTECTED]  (pref) | Snail: PO Box 370
[EMAIL PROTECTED] (alt) |Belconnen ACT 2616
Web:http://www.andymac.org/   |Australia
-- 
http://mail.python.org/mailman/listinfo/python-list


how to overload sqrt in a module?

2006-03-02 Thread Michael McNeil Forbes
I would like to write a module that provides some mathematical functions 
on top of those defined in math, cmath etc. but I would like to make it 
work with "any" type that overloads the math functions.

Thus, I would like to write:

module_f.py

def f(x):
""" Compute sqrt of x """
return sqrt(x)

>>> from math import *
>>> import module_f
>>> module_f.f(3)
Traceback (most recent call last):
File "", line 1, in ?
File "module_f.py", line 2, in f
  return sqrt(x)
NameError: global name 'sqrt' is not defined

I understand why sqrt is not in scope, but my question is: what is the 
best way to do this?

Here is one fairly ugly solution:

module_g.py
---
def g(x,math):
return math.sqrt(x)

>>> import math, cmath, module_g
>>> module_g.g(2,math)
1.4142135623730951
>>> module_g.g(-2,cmath)
1.4142135623730951j

I am sure there is a better way of doing this that makes use of the 
type of the argument (Dynamical scoping would solve the 
problem but we don't want to go there...).  Note that the following 
function would work fine

def f(x):
return abs(x)

because of the special member __abs__ attached to the type.  There is no 
corresponding member for sqrt, sin etc.

What is the "proper" pythonic way to do this?

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


Re: Printing a file

2006-03-02 Thread Fabian Steiner
David Boddie wrote:
> Sorry about that. I must have just skipped over the setup() call in
> your code. If you're creating highly customized content then I think
> you'll always need to think about getting the pages to the printer in
> the right order.
> 
> For rich text documents, there's code that does this in the Qt 3 text
> drawing demo (see the filePrint() method in the
> examples/demo/textdrawing/textedit.cpp file).
> 
> In Qt 4, the demos/textedit demo does this with a lot less code.
> 
> Or are you think of something else?

Thank you very much for this hint! Thanks to this example I was able to 
print out my first pages :)

But some questions still remain. At the moment I am using 
QSimpleRichtext and a personal HTML-File. I had a look at the 
example.html of textedit.cpp (/usr/share/doc/qt-4.1.1/demos/textedit) 
and found out that it contains quite a lot of proprietary HTML elements, 
attributes and CSS style definitions. So far I didn't even know that 
QSimpleRichText even supports CSS since I couldn't find anything related 
to this point in the official docs (--> e.g. QStylesheet).

Is there any tool out there with which I can write those special HTML 
files? I am quite familiar with HTML and CSS but I don't want to waste 
my time with that.

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


Re: in need of some sorting help

2006-03-02 Thread Ben Cartwright
ianaré wrote:
> However, i need the sorting done after the walk, due to the way the
> application works... should have specified that, sorry.


If your desired output is just a sorted list of files, there is no good
reason that you shouldn't be able sort in place.  Unless your app is
doing something extremely funky, in which case this should do it:

root = self.path.GetValue()  # wx.TextCtrl input
filter = self.fileType.GetValue().lower()  # wx.TextCtrl input
not_type = self.not_type.GetValue()  # wx.CheckBox input

matched_paths = {}
for base, dirs, walk_files in os.walk(root):
main.Update()
# i only need the part of the filename after the
# user selected path:
base = base.replace(root, '')

matched_paths[base] = []
for entry in walk_files:
entry = os.path.join(base, entry)
if not filter:
match = True
else:
match = filter in entry.lower()
if not_type:
match = not match
if match:
matched_paths[base].append(entry)

def tolower(x): return x.lower()
files = []
# Combine into flat list, first sorting on base path, then full
path
for base in sorted(matched_paths, key=tolower):
files.extend(sorted(matched_paths[base], key=tolower))

--Ben

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


Re: Write a GUI for a python script?

2006-03-02 Thread Grant Edwards
On 2006-03-02, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> Note that wxWindows wraps native widgets,

Not on Linux/KDE systems.  ;)

-- 
Grant Edwards   grante Yow!  ANN JILLIAN'S HAIR
  at   makes LONI ANDERSON'S
   visi.comHAIR look like RICARDO
   MONTALBAN'S HAIR!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do design patterns still apply with Python?

2006-03-02 Thread Terry Hancock
On Thu, 02 Mar 2006 16:38:44 -0500
Roy Smith <[EMAIL PROTECTED]> wrote:
> In article <[EMAIL PROTECTED]>,
>  John Salerno <[EMAIL PROTECTED]> wrote:
> > Since Python does so many things different, especially
> > compared to  compiled and statically typed languages, do
> > most of the basic design  patterns still apply when
> > writing Python code? If I were to read a  design pattern
> > book (such as Head First Design Patterns), could I apply
> > their Java examples to Python easily enough, or does
> > Python require a  different perspective when applying
> > patterns?
> [...]
> The basic concepts in the pattern books are worth knowing.
>  You just have 
> to be able to tease apart the concepts from the
> language-specific cruft  that so often obfuscates the
> descriptions. 

This sounds like an article crying out to be written,
"(Learning) Design Patterns with Python".

Has it been written already?

Cheers,
Terry

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

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


Re: do design patterns still apply with Python?

2006-03-02 Thread ajones
John Salerno wrote:
> Yeah, that's what I was wondering. I wonder if, after reading a DP book,
> I might have to 'unlearn' some things when applying them to Python.

I would say adjust instead of unlearn. This is probably true to a
lesser or greater extent of any language for which your DP book was not
written.

> But I suppose I should just do it first and then try to implement them
> myself. OOP is just so mind-bending for me that I've kind of put off
> patterns right now until I get more comfortable with it.  :)

I would suggest getting a good grasp on OOP before you get into design
patterns. When most people start with any new concept they tend to try
and see everything in terms of their new toy, so sticking to one or two
new concepts at a time will make things a little easier.

Design patterns are kind of like sarcasm: hard to use well, not always
appropriate, and disgustingly bad when applied to problems they are not
meant to solve. You will do just fine without them until OOP is at
least familiar to you, and by that time you should be a little better
able to use them appropriately.

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


Re: Write a GUI for a python script?

2006-03-02 Thread [EMAIL PROTECTED]
John M. Gabriele wrote:
> -- GTK+ is what most Gnome apps use. The Python binding is PyGTK.
> http://www.pygtk.org/
[snip]
> -- wxWindows is a lot like MS Windows MFC if I recall correctly.
> The Python binding to wxWindows is called wxPython.
> http://www.wxpython.org/

Note that wxWindows wraps native widgets, so a wxPython application
will use the native Windows widgets on windows, gtk widgets on
Linux/GNOME, Mac widgets on the Mac, etc.

I usually use wxPython for application development, but for my window
manager I'm using pygtk since it needs to be somewhat lower level and
portability to other platforms isn't a concern (turns out even that
isn't quite low-level enough for some things, so I drop down to
accessing the X event queue directly from C in a couple of cases).

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


Re: string stripping issues

2006-03-02 Thread orangeDinosaur
thanks!

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


Re: string stripping issues

2006-03-02 Thread Ben Cartwright
Ben Cartwright wrote:
> orangeDinosaur wrote:
> > I am encountering a behavior I can think of reason for.  Sometimes,
> > when I use the .strip module for strings, it takes away more than what
> > I've specified.  For example:
> >
> > >>> a = 'Hughes. John\r\n'
> >
> > >>> a.strip('')
> >
> > returns:
> >
> > 'ughes. John\r\n'
> >
> > However, if I take another string, for example:
> >
> > >>> b = 'Kim, Dong-Hyun\r\n'
> >
> > >>> b.strip('')
> >
> > returns:
> >
> > 'Kim, Dong-Hyun\r\n'
> >
> > I don't understand why in one case it eats up the 'H' but in the next
> > case it leaves the 'K' alone.
>
>
> That method... I do not think it means what you think it means.  The
> argument to str.strip is a *set* of characters, e.g.:
>
>   >>> foo = 'abababaXabbaXababa'
>   >>> foo.strip('ab')
>   'XabbaX'
>   >>> foo.strip('aabababaab') # no difference!
>   'XabbaX'
>
> For more info, see the string method docs:
> http://docs.python.org/lib/string-methods.html
> To do what you're trying to do, try this:
>
>   >>> prefix = 'hello '
>   >>> bar = 'hello world!'
>   >>> if bar.startswith(prefix): bar = bar[:len(prefix)]
>   ...
>   >>> bar
>   'world!'


Apologies, that should be:
   >>> prefix = 'hello '
   >>> bar = 'hello world!'
   >>> if bar.startswith(prefix): bar = bar[len(prefix):]
   ...
   >>> bar
   'world!'

--Ben

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


Re: Best python module for Oracle, but portable to other RDBMSes

2006-03-02 Thread skip

dananrg> Are you saying I'm getting the "L" as an artifact of printing?

No, you're getting the "L" because you're printing a long integer.  If you
execute

x = 872L
y = 872

at a Python prompt, x will be a long integer and y will be an integer.  Long
integers can represent arbitrarily large numbers (subject only to memory
limitations).  Integers are signed objects that are generally the same size
as the C long int type.  They are currently two more-or-less distinct types.
As time goes on they are converging though.  By the time Python 3.0 is
released I suspect there will be no difference.

If passing a long integer to some other routine is a problem (because it can
only accept regular integers) you can always convert it explicitly:

z = int(x)

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


Re: string stripping issues

2006-03-02 Thread ianaré
from the python manual:

strip( [chars])
The chars argument is not a prefix or suffix; rather, all combinations
of its values are stripped:
>>> 'www.example.com'.strip('cmowz.')
'example'

in your case since the letter 'H' is in your [chars] and the name
starts with an H it gets stripped, but with the second one the first
letter is a K so it stops there.
Maybe you can use:

>>> a[31:]
'Hughes. John\r\n'
>>> b[31:]
'Kim, Dong-Hyun\r\n'

but maybe what you REALLY want is:

>>> a[31:-14]
'Hughes. John'
>>> b[31:-14]
'Kim, Dong-Hyun'

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


Re: setattr question

2006-03-02 Thread Gerard Flanagan
Fredrik Lundh wrote:
> Gerard Flanagan wrote:
>
> > I have the following code:
> >
> >  builder.py #
> > class HtmlBuilder(object):
> >
> > @staticmethod
> > def page(title=''):
> > return HtmlPage(title)
> >
> > @staticmethod
> > def element(tag, text=None, **attribs):
> > return HtmlElement(tag, text, **attribs)
> >
> > @staticmethod
> > def literal(text):
> > return HtmlLiteral(text)
>
> just curious, but what's the purpose of this class, and what gave
> you the idea to structure your program in this way ?
>
> 

In my defense, I can only quote Albert Einstein: "If we knew what it
was we were doing, it would not be called research, would it?"  I'm
writing a script to generate a few relatively static webpages and
upload them to a server, but it's as much a learning exercise as
anything else - I have no formal programming education. I thought the
Factory pattern would be appropriate here; the class you quote was a
first attempt and i knew it was undoubtedly the wrong approach, so
that's why i asked the group...

Gerard

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


Re: string stripping issues

2006-03-02 Thread Ben Cartwright
orangeDinosaur wrote:
> I am encountering a behavior I can think of reason for.  Sometimes,
> when I use the .strip module for strings, it takes away more than what
> I've specified.  For example:
>
> >>> a = 'Hughes. John\r\n'
>
> >>> a.strip('')
>
> returns:
>
> 'ughes. John\r\n'
>
> However, if I take another string, for example:
>
> >>> b = 'Kim, Dong-Hyun\r\n'
>
> >>> b.strip('')
>
> returns:
>
> 'Kim, Dong-Hyun\r\n'
>
> I don't understand why in one case it eats up the 'H' but in the next
> case it leaves the 'K' alone.


That method... I do not think it means what you think it means.  The
argument to str.strip is a *set* of characters, e.g.:

  >>> foo = 'abababaXabbaXababa'
  >>> foo.strip('ab')
  'XabbaX'
  >>> foo.strip('aabababaab') # no difference!
  'XabbaX'

For more info, see the string method docs:
http://docs.python.org/lib/string-methods.html
To do what you're trying to do, try this:

  >>> prefix = 'hello '
  >>> bar = 'hello world!'
  >>> if bar.startswith(prefix): bar = bar[:len(prefix)]
  ...
  >>> bar
  'world!'

--Ben

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


Re: wxPython memory footprint? - Re: Write a GUI for a python script?

2006-03-02 Thread ianaré
> What is the minimal memory footprint of a Hello World wxPython app
> meanwhile (when you cx_freeze/py2exe it)

it's kinda weird actually... I'm not 100% sure, but i think it relates
more to py2exe options, not neccessarily to wxPython. in any case the
least memory usage i've seen for an app that has at least some degree
of functionality is around 12k running on win2000. But a much more
complicated and larger app uses about 16k, while another small app uses
like 20k...
???

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


Re: import, from and reload

2006-03-02 Thread Dave Benjamin
On Thu, 2 Mar 2006, John Salerno wrote:

> Dave Benjamin wrote:
>
>> In general, "from X import *" should be avoided anyway, for reasons that 
>> have been discussed many times in the past. The annoyance with reloading is 
>> just one more reason. Better to just use "import X" in the first place.
>
> Thanks. I kind of figured it's better to use import instead of from anyway, 
> but I was following along with some examples that use from (despite the fact 
> that earlier in the book they even say that from is problematic and you 
> should use import instead!)  :)

No problem. I stand by my original advice, but there is one semi-oneliner 
that you might find useful:

reload(__import__('X')); from X import *

You could keep that in your clipboard and paste it into the interpreter 
when you need to reload.

-- 
.:[ dave benjamin -( ramen/sp00 )- http://spoomusic.com/ ]:.
"one man's constant is another man's variable" - alan perlis
-- 
http://mail.python.org/mailman/listinfo/python-list


string stripping issues

2006-03-02 Thread orangeDinosaur
Hello,

I am encountering a behavior I can think of reason for.  Sometimes,
when I use the .strip module for strings, it takes away more than what
I've specified.  For example:

>>> a = 'Hughes. John\r\n'

>>> a.strip('')

returns:

'ughes. John\r\n'

However, if I take another string, for example:

>>> b = 'Kim, Dong-Hyun\r\n'

>>> b.strip('')

returns:

'Kim, Dong-Hyun\r\n'

I don't understand why in one case it eats up the 'H' but in the next
case it leaves the 'K' alone.

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


Re: Best python module for Oracle, but portable to other RDBMSes

2006-03-02 Thread dananrg
> If you actually get a suffixed L in the resulting text file, you
> are using a strange way to convert your data to text. You aren't
> simply printing lists or tuples are you? Then other types, such as
> datetime objects will also look bizarre. (Not that the ancient
> odbc would support that...)
> You might want to look at the csv module for text export.

Thanks Magnus. I didn't know there was a csv module.

Here's how I'm getting the suffixed "L"

import dbi, odbc   # Import ODBC modules
connectString = 'odbc_con_name/username/password'
dbc = odbc.odbc(connectString)# Connect to Oracle
cursor = dbc.cursor()# Create cursor
sql = "select statement here..." # Define SQL statement
cursor.execute(sql)  # Execute sql statement
allRecords = cursor.fetchall()   # Fetch all returned records
into a list of tuples
numRecords = len(allRecords) # Get num of records returned by
the query

# Note: I'm leaving out the for loop for this example...

# Print first record:
print allRecords[0]

>>> (872L, 'ACTIVE', , >> 010C2ED0>, None, '1.0.0.0', None, None, None)

# Convert first tuple to a list so I have a mutable object
recordList = list(allRecords[0])

# Print new list
print recordList

>>> [872L, 'ACTIVE', , >> 00EA1428>, None, '1.0.0.0', None, None, None]

# Convert long integer to short integer (int) to get rid of the "L"
recordList[0] = int(recordList[0])

# Print list with changed item. No more "L"
print recordList[0]

>>> [872, 'ACTIVE', , , 
>>> None, '1.0.0.0', None, None, None]
# The End

Are you saying I'm getting the "L" as an artifact of printing?

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


Re: do design patterns still apply with Python?

2006-03-02 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 John Salerno <[EMAIL PROTECTED]> wrote:

> Since Python does so many things different, especially compared to 
> compiled and statically typed languages, do most of the basic design 
> patterns still apply when writing Python code? If I were to read a 
> design pattern book (such as Head First Design Patterns), could I apply 
> their Java examples to Python easily enough, or does Python require a 
> different perspective when applying patterns?

Many of the classic design patterns apply just fine to Python, at least in 
the high-level view.  On the other hand, much (most?) of what's in the 
classic design pattern books is so tied up with ways around C++/Java type 
bondage, it's difficult to see the forest for the trees.

For example, take the most classic of all patterns, Singleton.  A typical 
C++ Singleton treatment will be all about making constructors private and 
shit like that.  None of that carries over to Python.  What I would do in 
Python is have a module-level factory function which caches a single 
instance of the class to return to the 2nd and subsequent caller and not 
get my panties in a twist over the fact that some clever programmer could 
find away around my code and force creation of a second instance.

The basic concepts in the pattern books are worth knowing.  You just have 
to be able to tease apart the concepts from the language-specific cruft 
that so often obfuscates the descriptions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Shared memory

2006-03-02 Thread Paddy
Pylinda ?
 http://www-users.cs.york.ac.uk/~aw/pylinda/

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


Re: how do you move to a new line in your text editor?

2006-03-02 Thread Tim Chase
> I use Vim, use spaces, and have no problems. It has a 
> shorttabstop option, which causes backspace to backspace 
> to the preceding multiple of  spaces when the 
> curser is after a set of spaces at the beginning of the 
> line. It feels like I'm using tabs, but I'm not.

In addition, within insert-mode in vim, you can use
control+D and control+T to exdent/indent the current one
'shiftwidth' worth.  If your 'shiftwidth' setting is the
same as your 'tabstop' setting, you'll get the expected
behavior.  There are also settings to control whether tabs
get interpreted as spaces or vice-versa (see ":help
expandtab").  I presume Emacs has similar settings.
However, Vim can be tweaked to handle whatever style you're
comfortable with (or whatever style management shoves down
on you).  The "shiftwidth = tabstop" also holds for the ">"
and "<" operators, so in Normal mode, you can use ">>" to
indent the current line, or "<3j" to exdent the current line
and the three below it.  All sorts of magic can be worked
with this :)

> Also, there's some Python indenting/folding macros I 
> picked up from Vim Online (don't remember where exactly),
>  that provide an indent/outdent pair of key mappings, 
> which also work perfectly with my usage of 4 spaces.

If you pop over to www.vim.org you'll find a search
functionality to search both the "tips" and "scripts"
section.  Just searching for "python" yields a bounty of
fun.  For folding, because python uses indenting, you can
just set your 'foldmethod' setting to "manual".

Okay...this has drifted just a wee spot off-topic.  However,
the vim mailing list is a friendly place--so if you have any
questions, feel free to drop in.

-tkc







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


Re: setattr question

2006-03-02 Thread Gerard Flanagan
bruno at modulix wrote:
> Gerard Flanagan wrote:
> > Hello
> >
> > I have the following code:
> >
> >  builder.py #
> > class HtmlBuilder(object):
> >
> > @staticmethod
> > def page(title=''):
> > return HtmlPage(title)
> >
> > @staticmethod
> > def element(tag, text=None, **attribs):
> > return HtmlElement(tag, text, **attribs)
> >
> > @staticmethod
> > def literal(text):
> > return HtmlLiteral(text)
>
> Je ne vois pas très bien à quoi sert cette classe (à moins bien sûr
> qu'il y ait d'autre code). Pour ce que je vois là, pourquoi ne pas
> appeler directement les classes HtmlPage, HtmlElement et HtmlLiteral ?
>

C'est une vaine tentative d'appliquer "the Factory Pattern" ! J'ai eu
commence d'ecrire les classes 'ul(HtmlElement), li(HtmlElement), etc ',
et le but de 'HtmlElementFactory' etait d'eviter ceci (cela?).  Il y a
une recette ici:

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

mais il utilise 'apply', qui est...blah

I was trying to implement the factory pattern.
The recipe above uses 'apply' which is deprecated according to the
docs, and I suppose I was curious how to do the same sort of thing
without 'apply'.

> Err... I don't see the point of this class. Why not just calling the
> HtmlPage|Element|Literal classes directly ?
>
> > class HtmlElementFactory(object):
> >
> > def __init__(self):
> > for tag in ['li', 'ul']:
> > setattr( self, tag, HtmlBuilder.element(tag) )
> >
> > #
> >
> > and so I can do the following:
> >
> > html = HtmlElementFactory()
> > ul = html.ul
> > ul.attrib['class'] = 'default'
> > for i in range(3):
> > li = html.li
> > li.text = 'ghfhj'
> > ul.append(li)
> > print ul.to_string()
> >
> > but what I'd like to do is:
> >
> > html = HtmlElementFactory()
> > ul = html.ul( class='default' )
>
>
>
> > for i in range(3):
> > ul.append( html.li( 'ghfhj' )
> > print ul.to_string()
>
> 'to_string' ?
> Let's see... 'to_string', a class with only staticmethods in it...
> You're coming from Java, aren't you ?-)
>

Never been to Java in my life!
I don't know if I understand you, HtmlElement has a 'to_string' method
but no static methods:

class HtmlElement(list):

def __init__(self, tag, text=None, **attrib):
self.tag = tag
self.text = text
self.attrib = attrib

def write(self, writer):
writer.start(self.tag, self.attrib)
if self.text is not None:
writer.data(self.text)
for node in self:
node.write(writer)
writer.end()

def to_string(self):
out = StringIO()
writer = HtmlWriter(out)
self.write(writer)
ret = out.getvalue()
out.close()
return ret

> (if yes, google for "python is not java", it may be helpful)
>
> > ie. to pass along *args and **kwargs to the HtmlElement constructor.
> > Any suggestions?
>
> yes : pass along *args and **kwargs to the HtmlElement constructor !-)
>
>
> > Or is there a better way to this kind of thing?
>
> yes again : kiss (Keep It Simple Stupid)
>
> There's not enough code to really grasp what you're trying to do, but
> from what I see, I'd say you're having a bad case of arbitrary
> overcomplexification.
>

My code itself is just a learning project ( etant sans emploi a ce
moment, moi-meme...) and it is no doubt a bit 'over-egged' at the
minute, but it is a first attempt and I can always refactor later.

> What's wrong with:
>
> # nb: class is a reserved word in Python
> ul = HtmlElement('ul', css_class='default')
> for i in range(3):
>   ul.append(HtmlElement('li', 'baaz%d' % i)
>
> # nb2: use the __str__() method of HtmlElement
> print str(ul)
>
> Python's philosophy is to make simple things simple (don't worry,
> there's still space for complex things -> descriptors, metaclasses etc).
>
> HTH
> --
> bruno desthuilliers
> python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
> p in '[EMAIL PROTECTED]'.split('@')])"

Merci bien pour votre reponse.

Gerard

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


Re: wxPython memory footprint? - Re: Write a GUI for a python script?

2006-03-02 Thread Chris Mellon
On 3/2/06, robert <[EMAIL PROTECTED]> wrote:
> ianaré wrote:
>
> > wxPython is another good option, especially since there is
> > boa-constructor, which is a great GUI builder, almost makes it too easy
> > to make a nice looking app in no time at all.
> >
> > http://www.wxpython.org/download.php
> >
> > http://boa-constructor.sourceforge.net/
> >
> > if you decide to give wxPython a go, make sure to download the demo, it
> > has tons of usefull code samples.
>
> What is the minimal memory footprint of a Hello World wxPython app
> meanwhile (when you cx_freeze/py2exe it) ?
>

I'm assuming you mean disk space and not memory usage. A stock
wxPython (from a standard release) wil vary from platform to platform
but is generally about 2.5 megs. This can be brought down rather a lot
if you're willing to spend a fair amount of time learning the
wxWidgets and wxPython build systems and making custom builds but it's
not generally worth the time to me (and I know the build system and
could make customized builds if I wanted to)

I have a non-trivial wxPython application and, using py2exe in "single
executable" mode (thus all the dlls and the zipfile with the .pyc
files are included in the exe) it's just over 5 megs in size.

> Can you debug & call functions interactively from e.g. Pythonwin while a
> wxPython app is running.
>

I've never tried it with PythonWin and I don't know how PythonWin
hooks into Python to manage debugging). Both pdb and the debugger in
PyDev work fine for me, however. As another responder said it's
trivial (literally < 5 lines) to add an interactive Python shell to a
wxPython application, which is invaluable for debugging and testing.

> ( When I made a test with wxPython some years ago, it had no option to
> step/share its Messageloop. Interaction was "crust"y and I didn't manage
> to get smooth debugging (on Windows).  )
>

I don't believe that wxPython exposes the low level C++ APIs that're
available to hook the wx message loop (it's an efficency issue, from
what I understand), but there are a number of other methods for
integration. The need to hook the message loop is far far less common
than the number of people who ask for it, so you'll forgive me if I'm
skeptical unless someone actually says why they want to.

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


Re: Simple System Tray Icon

2006-03-02 Thread 3c273
quoted
This is untested, 'cos I'm on a Mac these days, but what you want
should look something like:

from SysTrayIcon import SysTrayIcon
icon = SysTrayIcon('parh/to/icon.ico', "Hover text", {})

How simple do you want?

/quoted

I guess I still don't get it. The code you supplied creates an icon and then
hangs.

from SysTrayIcon import SysTrayIcon
icon = SysTrayIcon('PathToMyIcon', "My Application",())
while 1:
DoStuff()

DoStuff doesn't do happen until I choose 'QUIT' from the icon menu. Any
help? I feel like I'm missing something really fundamental here. Thanks
again.

Louis


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


Re: do design patterns still apply with Python?

2006-03-02 Thread Grant Edwards
On 2006-03-02, John Salerno <[EMAIL PROTECTED]> wrote:

> Since Python does so many things different, especially compared to 
> compiled and statically typed languages, do most of the basic design 
> patterns still apply when writing Python code?

Definitely.  Especially plaid, paisley, and a nice medium
houndstooth check.  But please, not all at the same time.

-- 
Grant Edwards   grante Yow!  Maybe we could paint
  at   GOLDIE HAWN a rich PRUSSIAN
   visi.comBLUE --
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do design patterns still apply with Python?

2006-03-02 Thread John Salerno
[EMAIL PROTECTED] wrote:

> In python, you might find it more natural to do design patterns in a
> completely different way than they're implemented in Java.  For
> example, I've heard of using the Singleton pattern in python by just
> implementing it as a module, no classes necessary.


Yeah, that's what I was wondering. I wonder if, after reading a DP book, 
I might have to 'unlearn' some things when applying them to Python. But 
I suppose I should just do it first and then try to implement them 
myself. OOP is just so mind-bending for me that I've kind of put off 
patterns right now until I get more comfortable with it.  :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how do you move to a new line in your text editor?

2006-03-02 Thread Michael Ekstrand
On Thu, 02 Mar 2006 18:39:55 GMT
John Salerno <[EMAIL PROTECTED]> wrote:
> But I read in the PEP that spaces are recommended over tabs. If this is 
> the case, it would involve pressing backspace 4 times (or 8, etc.) to 
> get back to column 1.
> 
> So I'm wondering, how do you all handle moving around in your code in 
> cases like this? Is there some sort of consistency to these things that 
> you can write rules for your text editor to know when to outdent? It 
> doesn't seem like you can do this reliably, though.

I use Vim, use spaces, and have no problems. It has a shorttabstop
option, which causes backspace to backspace to the preceding multiple
of  spaces when the curser is after a set of spaces at the
beginning of the line. It feels like I'm using tabs, but I'm not.

Also, there's some Python indenting/folding macros I picked up from Vim
Online (don't remember where exactly), that provide an indent/outdent
pair of key mappings, which also work perfectly with my usage of 4
spaces.

- Michael

-- 
mouse, n: a device for pointing at the xterm in which you want to type.
-- Fortune
-- 
http://mail.python.org/mailman/listinfo/python-list


pickle and converting to new-style classes

2006-03-02 Thread [EMAIL PROTECTED]
Hi,

I have a fairly sizable body of python code that I'm in the process of
modernizing.

One of the modernization steps is converting to use new-style classes,
and this is leading to problems with pickle. What's happening is that
part of the test suite for this code includes pickled instances of the
classes I am modifying, attempting to unpickle these objects is
generating errors in certain cases.

A bit of sample code that shows the same problem:

import pickle

# original class definition:
class klass:
  def __init__(self,v):
self._v=v

# instantiate it:
o = klass(3)
# create a pickle (simulates our saved pickle on disc)
pkl = pickle.dumps(o)

# change the class definition (simulates changing the orginal
# source):
class klass(object):
  def __init__(self,v):
self._v=v

# this generates an error:
n = pickle.loads(pkl)


There error I get is:
Traceback (most recent call last):
  File "newclass.py", line 20, in ?
n = pickle.loads(pkl)
  File "c:\Python23\Lib\pickle.py", line 1394, in loads
return Unpickler(file).load()
  File "c:\Python23\Lib\pickle.py", line 872, in load
dispatch[key](self)
  File "c:\Python23\Lib\pickle.py", line 1084, in load_inst
self._instantiate(klass, self.marker())
  File "c:\Python23\Lib\pickle.py", line 1074, in _instantiate
value = klass(*args)
TypeError: in constructor for klass: __init__() takes exactly 2
arguments (1 given)

I realize I'm trying to do something a bit hackish, but re-generating
these pickled instances from scratch would be a rather massive amount
of work, so I'd really like to figure out some way to either
"translate" the pickled instances to work with the new-style class
definitions or to modify the class definition itself so that the
pickles can be loaded (this would be preferable). Is this remotely
possible?

thanks,
-greg

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


Re: do design patterns still apply with Python?

2006-03-02 Thread [EMAIL PROTECTED]
Hi John.

Design patterns aren't tied to any specific implementation so they
should apply to any language.  You might find that they can even apply
to solution domains outside of computer science.

Implementation details will usually differ between languages.  But the
implementation can also be different using the same language.  For
example, you can use Java to implement the Model View Controller design
pattern when writing a web site or when writing a database engine --
the implementation will be very different, but both will be MVC.

In python, you might find it more natural to do design patterns in a
completely different way than they're implemented in Java.  For
example, I've heard of using the Singleton pattern in python by just
implementing it as a module, no classes necessary.

sjbrown

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


Re: setattr question

2006-03-02 Thread Fredrik Lundh
Gerard Flanagan wrote:

> I have the following code:
>
>  builder.py #
> class HtmlBuilder(object):
>
> @staticmethod
> def page(title=''):
> return HtmlPage(title)
>
> @staticmethod
> def element(tag, text=None, **attribs):
> return HtmlElement(tag, text, **attribs)
>
> @staticmethod
> def literal(text):
> return HtmlLiteral(text)

just curious, but what's the purpose of this class, and what gave
you the idea to structure your program in this way ?





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


Re: wxPython memory footprint? - Re: Write a GUI for a python script?

2006-03-02 Thread Michael Ekstrand
On Thu, 02 Mar 2006 19:52:34 +0100
robert <[EMAIL PROTECTED]> wrote:
> Can you debug & call functions interactively from e.g. Pythonwin while a 
> wxPython app is running.

It's a snap to incorporate a nice GUI Python shell with object browser
into any wxPython app - wxPython provides its PyCrust shell as a
package, which provides your choice of a widget you can embed or a
top-level window you can create. In one app I worked on I created a
menu item that launched such a shell window, so I could poke around
inside the app.

As far as actual debugging/stepping... I'm not sure. I haven' thad much
luck with Python debugging using anything but Wing IDE.

- Michael

-- 
mouse, n: a device for pointing at the xterm in which you want to type.
-- Fortune
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does '#hash' mean anything in IDLE?

2006-03-02 Thread John Salerno
John Coleman wrote:
> John Coleman wrote:
>> Greetings,
>>I am currently trying to learn Python through the excellent
>> "Learning Python" book. 

me too!

> It isn't just #hash, but also things like #dict, #int, #len at the
> start of a comment line which defeats IDLE's colorization algorithm.
> Interestingly, things like #while or #for behave as expected so it
> seems to be built-ins rather than keywords which are the problem. To
> answer my own question - this is pretty clearly a (harmless) bug.

also notice that putting a space after # stops the problem
-- 
http://mail.python.org/mailman/listinfo/python-list


do design patterns still apply with Python?

2006-03-02 Thread John Salerno
Since Python does so many things different, especially compared to 
compiled and statically typed languages, do most of the basic design 
patterns still apply when writing Python code? If I were to read a 
design pattern book (such as Head First Design Patterns), could I apply 
their Java examples to Python easily enough, or does Python require a 
different perspective when applying patterns?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does '#hash' mean anything in IDLE?

2006-03-02 Thread John Coleman

John Coleman wrote:
> Greetings,
>I am currently trying to learn Python through the excellent
> "Learning Python" book. I wrote my first non-trivial program, which
> began with several comment lines. One of the comment lines began  with
> '#hash'. IDLE doesn't colorize it as a comment line but instead colors
> the word 'hash' in purple as if it were a key word. Wierd. The behavior
> seems easy to trigger: Just open up a new window in IDLE and enter
> these two lines:
>
> #This is a test
> #hash should still be a comment line
>
> Then, after saving, the second line is not colored as a comment line
> though the first is.
> Is this a bug, or do comment lines which begin with #hash have some
> special meaning?
> My program ran fine, so it seems that the interpreter itself is
> ignoring the line.
>
> -John Coleman

It isn't just #hash, but also things like #dict, #int, #len at the
start of a comment line which defeats IDLE's colorization algorithm.
Interestingly, things like #while or #for behave as expected so it
seems to be built-ins rather than keywords which are the problem. To
answer my own question - this is pretty clearly a (harmless) bug.

-John Coleman

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


Does '#hash' mean anything in IDLE?

2006-03-02 Thread John Coleman
Greetings,
   I am currently trying to learn Python through the excellent
"Learning Python" book. I wrote my first non-trivial program, which
began with several comment lines. One of the comment lines began  with
'#hash'. IDLE doesn't colorize it as a comment line but instead colors
the word 'hash' in purple as if it were a key word. Wierd. The behavior
seems easy to trigger: Just open up a new window in IDLE and enter
these two lines:

#This is a test
#hash should still be a comment line

Then, after saving, the second line is not colored as a comment line
though the first is.
Is this a bug, or do comment lines which begin with #hash have some
special meaning?
My program ran fine, so it seems that the interpreter itself is
ignoring the line.

-John Coleman

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


Re: why does close() fail miserably on popen with exit code -1 ?!

2006-03-02 Thread Tobiah
Still:

phase:toby:~> echo 'exit -1' | bash
phase:toby:~> echo $?
255
phase:toby:~> 


Jeffrey Schwab wrote:
> Atanas Banov wrote:
> 
>> i ran onto this weirdness today: seems like close() on popen-ed
>> (pseudo)file fails miserably with exception instead of returning exit
>> code, when said exit code is -1.
>>
>> here is the simplest example (under Windows):
>>
>>
> print popen('exit 1').close()
>>
>>
>> 1
>>
> print popen('exit -1').close()
>>
>>
>> Traceback (most recent call last):
>>   File "", line 1, in ?
>> IOError: (0, 'Error')
>>
> print popen('exit -2').close()
>>
>>
>> -2
>>
>> has anyone have idea why is that?
> 
> 
> _PyPclose returns the exit status of the popened process (the popenee?), 
> or -1 on error.  Of course, if the status is supposed to be -1, there's 
> some confusion.
> 
> In the snippet of code below (from Modules/posixmodule.c), result has 
> been initialized to the output of fclose, which in your case is 0.  The 
> comment is particularly handy.
> 
> if (result != EOF &&
> waitpid(pipe_pid, &exit_code, 0) == pipe_pid)
> {
> /* extract exit status */
> if (WIFEXITED(exit_code))
> {
> result = WEXITSTATUS(exit_code);
> }
> else
> {
> errno = EPIPE;
> result = -1;
> }
> }
> else
> {
> /* Indicate failure - this will cause the file object
>  * to raise an I/O error and translate the last
>  * error code from errno.  We do have a problem with
>  * last errors that overlap the normal errno table,
>  * but that's a consistent problem with the file object.
>  */
> result = -1;
> }
*** Free account sponsored by SecureIX.com ***
*** Encrypt your Internet usage with a free VPN account from 
http://www.SecureIX.com ***
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how do you move to a new line in your text editor?

2006-03-02 Thread John Salerno
Bill Scherer wrote:
> John Salerno wrote:
> 
>> I use UltraEdit right now, and it is possible to convert spaces and 
>> tabs back and forth, but it's just an extra step. I was thinking about 
>> trying vim, as I've heard it's easier to learn than emacs.
>>  
>>
> Absolutely. It's also easier to learn to ride a Huffy than a Schwinn, 
> Hondas are easier to drive than Toyotas, and Evian is easier to drink 
> than Poland Spring.
> 
> Do yourself a favor and learn them both. Then decide which is best for you.
> 
> Bill

Point taken. I like to just pick something and go with it, but sometimes 
I just need to experiment first.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: white space in expressions and argument lists

2006-03-02 Thread Scott David Daniels
Sybren Stuvel wrote:
> I just read the PEP where my way of alignment is under a 'NO' header.
> Too bad, since I think it can make things a lot clearer.

One reason is such code changes too much on code edits:
 foo= 'bar'
 foobar = 42
 azimov = 3
to:
 foo   = 'bar'
 something = 42
 azimov= 3

which makes code differences hard to read.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple System Tray Icon

2006-03-02 Thread 3c273

"Simon Brunning" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]

This is untested, 'cos I'm on a Mac these days, but what you want
should look something like:

from SysTrayIcon import SysTrayIcon
icon = SysTrayIcon('parh/to/icon.ico', "Hover text", {})

How simple do you want?


That's what I wanted. I just couldn't figure out how to use it. Thanks a
bunch.
Louis


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


Re: Write a GUI for a python script?

2006-03-02 Thread John M. Gabriele
John M. Gabriele wrote:
> 
> There are Python bindings to most GUI toolkits (GTK+, Qt, fltk, wxWindows,
> and Tk come to mind).

Whoops. Forgot fltk with the pyFLTK Python binding. fltk
is a fast, light, toolkit that's written in C++ but (again,
IIRC) feels more like C-with-classes (which isn't a bad thing).

---John
-- 
(remove zeez if demunging email address)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Shared memory

2006-03-02 Thread Michel Claveau
mmap?

-- 
@-salutations

Michel Claveau


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


Re: Write a GUI for a python script?

2006-03-02 Thread John M. Gabriele
Glurt Wuntal wrote:
> I am a newbie with Python. It's a great language, but I would like to be
> able to present a simple gui menu for some of my scripts; something better
> than using 'raw_input' prompts.
> 
> Any recommendations for a program that will allow me to create the gui
> screens? Something useable in Linux.
> 
> thanks.
> 

There are Python bindings to most GUI toolkits (GTK+, Qt, fltk, wxWindows,
and Tk come to mind). You could use any of them. They're all usable in
GNU/Linux.

-- Tk is a mature, small, and simple toolkit. The Python binding
to Tk is called Tkinter.

-- GTK+ is what most Gnome apps use. The Python binding is PyGTK.
http://www.pygtk.org/

-- Qt is what most KDE apps use. The Python binding is called PyQt.

-- wxWindows is a lot like MS Windows MFC if I recall correctly.
The Python binding to wxWindows is called wxPython.
http://www.wxpython.org/

-- For a terminal-based text-mode character-cell display program, you
could use ncurses. http://www.amk.ca/python/howto/curses/
http://gnosis.cx/publish/programming/charming_python_6.html


---John
-- 
(remove zeez if demunging email address)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: white space in expressions and argument lists

2006-03-02 Thread rtilley
John Salerno wrote:
> All of it was a joke?

You'd have to ask Guido that :)

I took it literally when I first read it b/c it made sense to me and I 
did not notice the date. I don't think it will ever be _required_ of all 
Python hackers, but I may be wrong.
-- 
http://mail.python.org/mailman/listinfo/python-list


re-posting: web.py, incomplete

2006-03-02 Thread _wolf
hi all,

this is a re-posting of my question i asked a month or so ago. i
installed web.py, flups, and cheetah. when i copy'n'paste the sample
app from then http://webpy.org homepage ::

import web

urls = (
'/(.*)', 'hello'
)

class hello:
def GET(self, name):
i = web.input(times=1)
if not name: name = 'world'
for c in xrange(int(i.times)): print 'Hello,', name+'!'
# point (1)

if __name__ == "__main__": web.run(urls)

it does seem to work *but* when i call it with sth like

http://localhost/cgi-bin/webpyexample.py/oops?times=25

then the output is ::

Hello, oops!
Hello, oops!
<20 lines omitted/>
Hello, oops!
Hel

it is only after i insert, at point (1) as shown in the listing, ::

print ( ( ' ' * 100 ) + '\n' ) * 10

---print ten lines with a hundred space characters each---that
i do get to see all twenty-five helloes. so, this is likely a
character buffering problem. as far as i can see, it is a consistent
amount of the last 32 characters that is missing from the page
source. ok i thought so let's just output those 32 characters, ::

print ' ' * 32

but *this* will result in a last output line that is 8 characters
long, so someone swallows 24 characters. does look like
a buffer of fixed length. 

i'd like to bust that ghost.

_wolf

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


Re: compare classes and not class instances

2006-03-02 Thread [EMAIL PROTECTED]
Awesome! Perfect!

Thanks
Janto

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


Re: Suggestions for documentation generation?

2006-03-02 Thread John M. Gabriele
Michael Ekstrand wrote:
> 
> 
> Doxygen has recently added support for Python, [snip]

Didn't know that. Thanks for the heads-up. :)

-- 
(remove zeez if demunging email address)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how do you move to a new line in your text editor?

2006-03-02 Thread John Salerno
Paul McNett wrote:

> That said, you should be able to tell your editor how to behave in the 
> indent/unindent case, no matter whether you use tabs or spaces. If not, 
> time to switch editors! ;)

I definitely can, I'm just a little unsure about what the special 
outdenting cases might be. The way to do it in UltraEdit is to specify 
which characters (on a preceding line) an outdented line should follow, 
so obviously for a C language you could specify Unindent = '}' and that 
would help a lot. But with Python it seems more difficult to figure out 
the cases where you would outdent.

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


Re: how do you move to a new line in your text editor?

2006-03-02 Thread John Salerno
Carl Banks wrote:

> You wouldn't know if Ultraedit has some kind of hook mechanism (whereby
> it can execute a macro or script or something upon loading/saving).
> That could solve your problem.  Obviously, having to manually convert
> isn't too helpful.

I'll have to check on that. I know I can do macros and such, but I'll 
have to see about having it done automatically.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how do you move to a new line in your text editor?

2006-03-02 Thread Bill Scherer
John Salerno wrote:

>I use UltraEdit right now, and it is possible to convert spaces and tabs 
>back and forth, but it's just an extra step. I was thinking about trying 
>vim, as I've heard it's easier to learn than emacs.
>  
>
Absolutely. It's also easier to learn to ride a Huffy than a Schwinn, 
Hondas are easier to drive than Toyotas, and Evian is easier to drink 
than Poland Spring.

Do yourself a favor and learn them both. Then decide which is best for you.

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


Re: how do you move to a new line in your text editor?

2006-03-02 Thread Carl Banks

John Salerno wrote:
> Carl Banks wrote:
> > John Salerno wrote:
> >> So I'm wondering, how do you all handle moving around in your code in
> >> cases like this? Is there some sort of consistency to these things that
> >> you can write rules for your text editor to know when to outdent? It
> >> doesn't seem like you can do this reliably, though.
> >
> > Emacs, at least, outdents reliably with spaces.  Probably some other
> > editors do as well, though I was kind of surprised to find out that
> > some editors have (compared to Emacs) weak indent inference.
> >
> > If editing with spaces annoys you, it might be possible with your
> > editor (which seems to have a variable tab stop) to edit the file with
> > tabs, but save it with spaces.
>
> I use UltraEdit right now, and it is possible to convert spaces and tabs
> back and forth, but it's just an extra step. I was thinking about trying
> vim, as I've heard it's easier to learn than emacs.

Well, they don't call vi the "Very Intuitive" editor for nothing.  I
suspect if you're not used to the modes and movement keys and stuff
it'll be a little steep learning at first.  More power to you if you
can get used to that.

You wouldn't know if Ultraedit has some kind of hook mechanism (whereby
it can execute a macro or script or something upon loading/saving).
That could solve your problem.  Obviously, having to manually convert
isn't too helpful.

Carl Banks

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


Re: how do you move to a new line in your text editor?

2006-03-02 Thread John Salerno
Carl Banks wrote:
> John Salerno wrote:
>> So I'm wondering, how do you all handle moving around in your code in
>> cases like this? Is there some sort of consistency to these things that
>> you can write rules for your text editor to know when to outdent? It
>> doesn't seem like you can do this reliably, though.
> 
> Emacs, at least, outdents reliably with spaces.  Probably some other
> editors do as well, though I was kind of surprised to find out that
> some editors have (compared to Emacs) weak indent inference.
> 
> If editing with spaces annoys you, it might be possible with your
> editor (which seems to have a variable tab stop) to edit the file with
> tabs, but save it with spaces.
> 
> 
> Carl Banks
> 

I use UltraEdit right now, and it is possible to convert spaces and tabs 
back and forth, but it's just an extra step. I was thinking about trying 
vim, as I've heard it's easier to learn than emacs.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >