Re: Do this as a list comprehension?

2008-06-06 Thread dwahli
On Jun 6, 8:44 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
>
> Of course, enumerate(iterable) is just a facade over zip(itertools.count(),
> iterable)

So you could write:
gen = (x for x in itertools.izip(itertools.count(8), [0, 1, 1, 1, 1,
1, 1, 2, 2, 3, 3]))
print list(gen)

Using zip like you own example is the best option.

If you have a huge amount of data and only want to iterate over the
result, using a generator is probably better:
gen = (x for x in itertools.izip(itertools.count(8), [0, 1, 1, 1, 1,
1, 1, 2, 2, 3, 3]))
for i, j in gen:
  ... your code here ...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Books for learning how to write "big" programs

2008-06-06 Thread Bob Martin
in 69148 20080605 140635 [EMAIL PROTECTED] wrote:
>On May 22, 12:49=A0pm, "Kurt Smith" <[EMAIL PROTECTED]> wrote:
>> On Thu, May 22, 2008 at 10:55 AM, duli <[EMAIL PROTECTED]> wrote:
>> > Hi:
>> > I would like recommendations forbooks(in any language, not
>> > necessarily C++, C, python) which have walkthroughs for developing
>> > a big software project ? So starting from inception, problem
>> > definition, design, coding and final delivery on a single theme
>> > or application.
>>
>> The bigger the project, the more likely it is that you'll have
>> documentation on how to use it (for a language or library, how to use
>> the features in your program) but to take the time to write up a
>> dead-tree book on the project's "inception, problem definition,
>> design, coding and final delivery" is not likely well spent. =A0Anyone
>> who has the expertise to write such a book would probably be spending
>> his time working on the next phase of the project itself.
>>
>> Someone will probably respond with an amazon link to a book that does
>> exactly what you're asking, in which case, I will stand corrected.
>> But I'll be surprised.
>>
>>
>>
>> > Most of the code I have written andbooksthat I have read deal with
>> > toy programs and I am looking for something a bit more
>> > comprehensive. =A0For example, maybe a complete compiler written in C++
>> > for some language, or a complete web server or implementing
>> > .net libraries in some language (just a few examples of the scale of
>> > things I am interested in learning).
>>
>> It seems to me the reason toy programs are so prevalent is because
>> they illustrate a (few) well defined ideas in a short amount of code.
>> A big project, necessarily, brings together all kinds of stuff, much
>> of which may not interest the author at all, and so doesn't motivate
>> him to write a book about it.
>>
>> Compilers, web servers & .NET libraries are *widely* varying areas.
>> You may have interest in them all, but to significantly contribute to
>> any requires a fair amount of expertise and specialization.
>>
>> The best route I've found to learn how to organize & program large
>> scale applications is this: find a cutting edge program that interests
>> you and that is open source. =A0Download its source, and read the code.
>> Diagram it. =A0Map it out. =A0Read the comments. =A0Join the mailing list
>> (probably the developer's list), lurk for a while, and ask questions
>> about why they organized things the way they did. =A0Get the overall big
>> picture and learn from it. =A0Better yet, find out what pitfalls they
>> found and avoided (or fell into). =A0Compare their approach &
>> organization with another competing project. =A0This is the wonder of
>> open source software -- you have access to everything, and can learn
>> from all the expertise the developers put into their opus.
>>
>> You can learn the basics frombooks, but nothing beats analyzing a
>> species in the wild.
>
>I think I have lately understood what you mean, thanks to Programming
>Python 3rd Ed by Lutz. It doesn't teach Python itself -- the book aims
>to teach Python programming at an application level, but I'm starting
>to wonder whether that knowledge can be obtained from any book. The
>book goes through over 1500 pages (!) giving small- and medium-sized
>example programs and describing their details. Roughly after a couple
>of hundred pages I started to feel like all that was trivial (isn't
>looking at code and figuring their details what we do in our every-day
>programmer lifes?), and then started to feel like it was really
>useless. Maybe large-scale programming can only be self-thought in
>every day life, am I right?.

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


Re: Why does python not have a mechanism for data hiding?

2008-06-06 Thread cokofreedom
Someone asked about Java;

class FieldTest {
public String publicString = "Foobar";
private String privateString = "Hello, World!";
}

import java.lang.reflect.Field;

public class Test4 {
  public static void main(String args[]) {
final Field fields[] =
FieldTest.class.getDeclaredFields();
for (int i = 0; i < fields.length; ++i) {
  System.out.println("Field: " + fields[i]);
}
  }
}

OUTPUT 
Field: public java.lang.String FieldTest.publicString
Field: private java.lang.String FieldTest.privateString

And to edit it;

import java.lang.reflect.Field;

public class Test7 {
  public static void main(String args[])
throws Exception {
final Field fields[] =
FieldTest.class.getDeclaredFields();
for (int i = 0; i < fields.length; ++i) {
  if ("privateString".equals(fields[i].getName())) {
FieldTest fieldTest = new FieldTest();
Field f = fields[i];
f.setAccessible(true);
System.out.println(f.get(fieldTest));
f.set(fieldTest, "Modified Field");
System.out.println(f.get(fieldTest));
break;
  }
}
  }
}

OUTPUT 
Hello, World!
Modified Field

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


Re: gcc error in Mac OS X

2008-06-06 Thread Zhaojie Boulder
Thank you all.
Finally the problem was solved by installing Xcode from the DVD which comes
with the computer. But installing the same program downloaded from apple
site always cause the gcc error.

Jie

2008/6/5 Mathieu Prevot <[EMAIL PROTECTED]>:

> 2008/6/6 Mathieu Prevot <[EMAIL PROTECTED]>:
> > 2008/6/5 Zhaojie Boulder <[EMAIL PROTECTED]>:
> >> Hello,
> >> I am new to Mac and used python in linux before. What I am trying to do
> is
> >> to install "Ipython" and "PyCogent" in Mac OS X.
> >> For PyCogent, after entering the package path, I typed "python setup.py
> >> install". The results are as follows:
> >> Didn't find Pyrex - will compile from .c files
> >> running install
> >> running build
> >> running build_py
> >> running build_ext
> >> building 'cogent.align._compare' extension
> >> gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp
> -mno-fused-madd
> >> -fno-common -dynamic -DNDEBUG -g -Os -Wall -Wstrict-prototypes -DMACOSX
> >> -I/usr/include/ffi -DENABLE_DTRACE -arch i386 -arch ppc -pipe
> >> -I/Users/zhaojie/Downloads/PyCogent-1.0.1/include
> >>
> -I/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5
> >> -c cogent/align/_compare.c -o
> >> build/temp.macosx-10.5-i386-2.5/cogent/align/_compare.o -w
> >> unable to execute gcc: No such file or directory
> >> error: command 'gcc' failed with exit status 1
> >> After google, I installed Xcode,but it did not help. Also, the Xcode
> folder
> >> is not within "applications" folder, but a separate one parallel with
> >> "applications". Dragging Xcode folder into the applications folder did
> not
> >> make a difference, either.
> >> Hope someone familiar with Mac can help me out.
> >
> > Normally gcc is installed in /usr/bin. If you type "which gcc", it
> > should return "/usr/bin/gcc". Xcode is an IDE that use gcc or another
> > compiler eg. icc the Intel compiler, hence if you move Xcode in the
> > application folfer it won't change anything. You install Xcode by
> > double clicking on a .pkg file from your Leopard DVD.
> >
> > You also can download gcc from the site and bootstrap/compile it.
>
> Note that you don't need to install Xcode in the "right place", it is
> normally installed in /Developer, and installs gcc and other files in
> /usr/bin /usr/share etc.
>
> In general, try "locate prog" to try to find where is prog, and check
> if the binary prog's path is in your PATH. eg. you can compile and
> install a gnu tool by ./configure --prefix=$HOME && make && make
> install, and the binaries will be installed in ~/bin/. If you don't
> have ~/bin/ in your PATH, it won't execute. Adding 'export
> PATH="$PATH:$HOME/bin:"' in your .bashrc will solve the problem (or
> 'setenv PATH "$PATH:$HOME/bin:' in your .tcshrc)
>
> Using --prefix=$HOME allow you to run and install your binaries and
> libraries. You can do this for a group of users without root access,
> so you can share, or preserve your OS bin/lib/include/share easily, or
> allow alternative use of several versions of libraries/binaries etc.
>
> Other possibilities are the chroot and the sophisticated FreeBSD
> jails. Google for them to know more.
>
> Hope that helps,
> Mathieu
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: Cannot use Winpdb (or PyDev) to trace embedded Python script in MSVC++ application - ImportError: No module named _socket

2008-06-06 Thread Nir
You seem to be having a problem with the import path of the embedded
interpreter. I suppose the embedded interpreter includes some modules
in a particular folder and _socket is not one of them. For the sake of
debugging try adding the c:\python25\lib path to the sys.path variable
of the interpreter before attempting to import rpdb2.

Does this work?

Nir


On Jun 5, 2:52 pm, [EMAIL PROTECTED] wrote:
> I am embedding Python in a MSVC++ (2005) application. The application
> creates some environment and then launches a Python script that will
> call some functions exported from the MSVC++ application.
>
> I want to be able to debug the Python script by using a debug server,
> likeWinpdb(winpdb.org).
>
> I use ActivePython 2.5.2.2, Microsoft Visual Studio 2005, andWinpdb
> 1.3.8.
>
> When I launch a script like "e:>python test.py" everything is O'K and
> I can useWinpdbto trace/debug.
>
> When I run the same script from the MSVC++ application, there is
> always a complain "ImportError: No module named _socket".
>
> Here is the basic test script I use:
>
>
>
> def Process( something ):
> print "\n\nStarted debugging\n=\n"
> #pydevd.settrace()
> import rpdb2; rpdb2.start_embedded_debugger("1")
> print "\n\nStopped debugging\n=\n"
>
> if __name__ == '__main__':
> Process( "test" )
> <<<
>
> In the MSVC++ application I tried many approaches, as suggested by
> many people, and all of them work to launch the script, but none of
> them works withWinpdb(or PyDev for Eclipse - same problem). Just for
> completeness - here is one:
>
>
>
>   PyRun_SimpleString("import sys");
>   PyRun_SimpleString("import os");
>   PyRun_SimpleString( "fullpath = os.path.abspath(\"E:/Test.py\")" );
>   PyRun_SimpleString( "g = globals().copy()" );
>   PyRun_SimpleString( "g['__file__'] = fullpath");
>   PyRun_SimpleString( "execfile(fullpath, g) ");
> <<<
>
> If I use pdb (import pdb + pdb.runcall(something) ) everything works
> fine, but I need the performance and convinience ofWinpdb.
>
> What am I doing wrong?
>
> Your help is highly appreciated!
>
> Best regards,
> Chris

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


import cherrypy2

2008-06-06 Thread luca72
Hello i can't import cherrypy2 but i don't know why this is the sys
path:

'', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
setuptools-0.6c7-py2.5.egg', '/home/pirataja/opo.net/python/lib/
python2.5/site-packages/TurboGears-1.0.4.4-py2.5.egg', '/home/pirataja/
opo.net/python/lib/python2.5/site-packages/TurboKid-1.0.4-py2.5.egg',
'/home/pirataja/opo.net/python/lib/python2.5/site-packages/
TurboJson-1.1.2-py2.5.egg', '/home/pirataja/opo.net/python/lib/
python2.5/site-packages/TurboCheetah-1.0-py2.5.egg', '/home/pirataja/
opo.net/python/lib/python2.5/site-packages/simplejson-1.9.1-py2.5-
linux-i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-
packages/RuleDispatch-0.5a0.dev_r2306-py2.5-linux-i686.egg', '/home/
pirataja/opo.net/python/lib/python2.5/site-packages/PasteScript-1.6.2-
py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
FormEncode-1.0.1-py2.5.egg', '/home/pirataja/opo.net/python/lib/
python2.5/site-packages/DecoratorTools-1.7-py2.5.egg', '/home/pirataja/
opo.net/python/lib/python2.5/site-packages/configobj-4.5.2-py2.5.egg',
'/home/pirataja/opo.net/python/lib/python2.5/site-packages/
CherryPy-2.3.0-py2.5.egg', '/home/pirataja/opo.net/python/lib/
python2.5/site-packages/kid-0.9.6-py2.5.egg', '/home/pirataja/opo.net/
python/lib/python2.5/site-packages/Cheetah-2.0.1-py2.5-linux-
i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
PyProtocols-1.0a0dev_r2302-py2.5-linux-i686.egg', '/home/pirataja/
opo.net/python/lib/python2.5/site-packages/PasteDeploy-1.3.1-
py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
Paste-1.7-py2.5.egg', '/home/pirataja/opo.net/python/lib/
python25.zip', '/home/pirataja/pirata-jacopo.net/python/lib/
python2.5', '/home/pirataja/opo.net/python/lib/python2.5/plat-
linux2',
'/home/pirataja/opo.net/python/lib/python2.5/lib-tk',
'/home/pirataja/opo.net/python/lib/python2.5/lib-dynload', '/home/
pirataja/opo.net/python/lib/python2.5/site-packages']

For my is all ok but whe i do import cherrypy2 i get no mudule name
cherrypy2

Regards

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


Re: import cherrypy2

2008-06-06 Thread Chris
On Jun 6, 10:22 am, luca72 <[EMAIL PROTECTED]> wrote:
> Hello i can't import cherrypy2 but i don't know why this is the sys
> path:
>
> '', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
> setuptools-0.6c7-py2.5.egg', '/home/pirataja/opo.net/python/lib/
> python2.5/site-packages/TurboGears-1.0.4.4-py2.5.egg', '/home/pirataja/
> opo.net/python/lib/python2.5/site-packages/TurboKid-1.0.4-py2.5.egg',
> '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
> TurboJson-1.1.2-py2.5.egg', '/home/pirataja/opo.net/python/lib/
> python2.5/site-packages/TurboCheetah-1.0-py2.5.egg', '/home/pirataja/
> opo.net/python/lib/python2.5/site-packages/simplejson-1.9.1-py2.5-
> linux-i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-
> packages/RuleDispatch-0.5a0.dev_r2306-py2.5-linux-i686.egg', '/home/
> pirataja/opo.net/python/lib/python2.5/site-packages/PasteScript-1.6.2-
> py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
> FormEncode-1.0.1-py2.5.egg', '/home/pirataja/opo.net/python/lib/
> python2.5/site-packages/DecoratorTools-1.7-py2.5.egg', '/home/pirataja/
> opo.net/python/lib/python2.5/site-packages/configobj-4.5.2-py2.5.egg',
> '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
> CherryPy-2.3.0-py2.5.egg', '/home/pirataja/opo.net/python/lib/
> python2.5/site-packages/kid-0.9.6-py2.5.egg', '/home/pirataja/opo.net/
> python/lib/python2.5/site-packages/Cheetah-2.0.1-py2.5-linux-
> i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
> PyProtocols-1.0a0dev_r2302-py2.5-linux-i686.egg', '/home/pirataja/
> opo.net/python/lib/python2.5/site-packages/PasteDeploy-1.3.1-
> py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
> Paste-1.7-py2.5.egg', '/home/pirataja/opo.net/python/lib/
> python25.zip', '/home/pirataja/pirata-jacopo.net/python/lib/
> python2.5', '/home/pirataja/opo.net/python/lib/python2.5/plat-
> linux2',
> '/home/pirataja/opo.net/python/lib/python2.5/lib-tk',
> '/home/pirataja/opo.net/python/lib/python2.5/lib-dynload', '/home/
> pirataja/opo.net/python/lib/python2.5/site-packages']
>
> For my is all ok but whe i do import cherrypy2 i get no mudule name
> cherrypy2
>
> Regards
>
> Luca

because it's "import cherrypy" and not "import cherrypy2"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help need with subprocess communicate

2008-06-06 Thread Nicola Musatti
On Jun 4, 9:56 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Tue, 3 Jun 2008 23:48:38 -0700 (PDT), [EMAIL PROTECTED] declaimed the
> following in comp.lang.python:
>
> > Is there way to configure the stdout buffer size so that it flushes
> > earlier..
> > Is there a way to make above mentioned piece code working?
>
> I believe there is a command line argument that will set Python into
> an unbuffered mode... BUT, unless the spawned process/program has some
> similar option, you have no control over its output.

Which is why the Cookbook recipe I pointed to in my other message
appears to be a superior alternative. Its author works around this
problem by subclassing Popen to use non blocking I/O.

I used it to drive ClearCase's cleartool interactive tool and it works
very well. The only problem I encountered is that it doesn't mix well
with framework that have their own event loop (wxPython in my case),
but you can't really expect that to work.

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


parsing .pcap files

2008-06-06 Thread Astan Chee

Hi,
Im using pyflag to parse .pcap files. Pyflag displays the data part of 
the .pcap file in binary and I was wondering what this means. How do I 
decode the 'data' part of the packet without using external libraries? 
What does these non-alpha numerical information mean? Is there a 
(python) dictionary/documentation somewhere that I can use to parse this 
data?

Thanks again.
Cheers
Astan
PS: I've attached the .pcap file that Im using to test and the python 
file as well.


--
"Formulations of number theory: Complete, Consistent, Non-trivial. Choose two."



Animal Logic
http://www.animallogic.com

Please think of the environment before printing this email.

This email and any attachments may be confidential and/or privileged. If you 
are not the intended recipient of this email, you must not disclose or use the 
information contained in it. Please notify the sender immediately and delete 
this document if you have received it in error. We do not guarantee this email 
is error or virus free.

# **
# Michael Cohen <[EMAIL PROTECTED]>
#
# **
#  Version: FLAG $Version: 0.86RC1 Date: Thu Jan 31 01:21:19 EST 2008$
# **
#
# * This program is free software; you can redistribute it and/or
# * modify it under the terms of the GNU General Public License
# * as published by the Free Software Foundation; either version 2
# * of the License, or (at your option) any later version.
# *
# * This program is distributed in the hope that it will be useful,
# * but WITHOUT ANY WARRANTY; without even the implied warranty of
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# * GNU General Public License for more details.
# *
# * You should have received a copy of the GNU General Public License
# * along with this program; if not, write to the Free Software
# * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
# **
""" A library for reading PCAP files.

PCAP format is really simple so this is a nobrainer. Good example of
using the file format library though. This shows how we can handle the
endianess issue simply.
"""
import struct,time,cStringIO
import sys

## This is the default size that will be read when not specified
DEFAULT_SIZE=600*1024*1024

class Buffer:
""" This class looks very much like a string, but in fact uses a file object.

The advantage here is that when we do string slicing, we are not duplicating strings all over the place (better performace). Also it is always possible to tell where a particular piece of data came from.
"""
def __init__(self,fd,offset=0,size=None):
""" We can either specify a string, or a fd as the first arg """
self.offset=offset
self.fd=fd
if size!=None:
self.size=size
else:
self.fd=fd
if size!=None:
self.size=size
else:
## Try to calculate the size by seeking the fd to the end
offset = fd.tell()
try:
fd.seek(0,2)
except Exception,e:
print "%s: %r" % (e,fd)
self.size=fd.tell()
fd.seek(offset)

#if self.size<0:
#raise IOError("Unable to set negative size (%s) for buffer (offset was %s)" % (self.size,self.offset))

def clone(self):
return self.__class__(fd=self.fd, offset=self.offset, size=self.size)

def __len__(self):
return self.size

def set_offset(self,offset):
""" This sets the absolute offset.

It is useful in files which specify an absolute offset into the file within some of the data structures.
"""
return self.__class__(fd=self.fd,offset=offset)

def __getitem__(self,offset):
""" Return a single char from the string """
self.fd.seek(offset+self.offset)
return self.fd.read(1)


## FIXME: Python slicing will only pass uint_32 using the syntax
def __getslice__(self,a=0,b=None):
""" Returns another Buffer object which may be manipulated completely independently from this one.

Note that the new buffer object references the same fd that we are based on.
"""
if b:
if b>self.size:
b=self.size
return self.__class__(fd=self.fd,offset=self.offset+a,size=b-a)
else:
return self.__class__(fd=self.fd,offset=self.offset+a)

def __str__(self):
self.fd.seek(self.offset)
if self.size>=0:
data=self.fd.read(self.size)
else:
data=self.fd.read(DEFAULT_SIZE)

#if len(data) < self.size:
#raise IOError("Unable to read %s bytes from %s" %(self.size,self.offset))

return data

def __nonzero__(self)

Re: import cherrypy2

2008-06-06 Thread luca72
On 6 Giu, 10:31, Chris <[EMAIL PROTECTED]> wrote:
> On Jun 6, 10:22 am, luca72 <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hello i can't import cherrypy2 but i don't know why this is the sys
> > path:
>
> > '', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
> > setuptools-0.6c7-py2.5.egg', '/home/pirataja/opo.net/python/lib/
> > python2.5/site-packages/TurboGears-1.0.4.4-py2.5.egg', '/home/pirataja/
> > opo.net/python/lib/python2.5/site-packages/TurboKid-1.0.4-py2.5.egg',
> > '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
> > TurboJson-1.1.2-py2.5.egg', '/home/pirataja/opo.net/python/lib/
> > python2.5/site-packages/TurboCheetah-1.0-py2.5.egg', '/home/pirataja/
> > opo.net/python/lib/python2.5/site-packages/simplejson-1.9.1-py2.5-
> > linux-i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-
> > packages/RuleDispatch-0.5a0.dev_r2306-py2.5-linux-i686.egg', '/home/
> > pirataja/opo.net/python/lib/python2.5/site-packages/PasteScript-1.6.2-
> > py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
> > FormEncode-1.0.1-py2.5.egg', '/home/pirataja/opo.net/python/lib/
> > python2.5/site-packages/DecoratorTools-1.7-py2.5.egg', '/home/pirataja/
> > opo.net/python/lib/python2.5/site-packages/configobj-4.5.2-py2.5.egg',
> > '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
> > CherryPy-2.3.0-py2.5.egg', '/home/pirataja/opo.net/python/lib/
> > python2.5/site-packages/kid-0.9.6-py2.5.egg', '/home/pirataja/opo.net/
> > python/lib/python2.5/site-packages/Cheetah-2.0.1-py2.5-linux-
> > i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
> > PyProtocols-1.0a0dev_r2302-py2.5-linux-i686.egg', '/home/pirataja/
> > opo.net/python/lib/python2.5/site-packages/PasteDeploy-1.3.1-
> > py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
> > Paste-1.7-py2.5.egg', '/home/pirataja/opo.net/python/lib/
> > python25.zip', '/home/pirataja/pirata-jacopo.net/python/lib/
> > python2.5', '/home/pirataja/opo.net/python/lib/python2.5/plat-
> > linux2',
> > '/home/pirataja/opo.net/python/lib/python2.5/lib-tk',
> > '/home/pirataja/opo.net/python/lib/python2.5/lib-dynload', '/home/
> > pirataja/opo.net/python/lib/python2.5/site-packages']
>
> > For my is all ok but whe i do import cherrypy2 i get no mudule name
> > cherrypy2
>
> > Regards
>
> > Luca
>
> because it's "import cherrypy" and not "import cherrypy2"

sorry but from another python installation i import cherrypy2 as
cherrypy and all works

Regards

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


Re: Do this as a list comprehension?

2008-06-06 Thread Marc 'BlackJack' Rintsch
On Thu, 05 Jun 2008 23:56:40 -0700, dwahli wrote:

> On Jun 6, 8:44 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
>>
>> Of course, enumerate(iterable) is just a facade over zip(itertools.count(),
>> iterable)
> 
> So you could write:
> gen = (x for x in itertools.izip(itertools.count(8), [0, 1, 1, 1, 1,
> 1, 1, 2, 2, 3, 3]))
> print list(gen)

Useless use of a generator expression.  This:

gen = itertools.izip(itertools.count(8), [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3])
print list(gen)

has the same effect without the intermediate generator that does nothing
but passing the items.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list

Re: import cherrypy2

2008-06-06 Thread luca72
No i haven't install lino

but if frmp the python of this computer  i make import cherrypy2 i
import it without problem this is the python path:

[EMAIL PROTECTED]:~> python
Python 2.5.1 (r251:54863, Jan 10 2008, 18:00:49)
[GCC 4.2.1 (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cherrypy2
>>> import sys
>>> sys.path
['', '/usr/lib64/python2.5/site-packages/setuptools-0.6c7-py2.5.egg',
'/usr/lib64/python2.5/site-packages/TurboGears-1.0.4.4-py2.5.egg', '/
usr/lib64/python2.5/site-packages/TurboKid-1.0.4-py2.5.egg', '/usr/
lib64/python2.5/site-packages/TurboJson-1.1.2-py2.5.egg', '/usr/lib64/
python2.5/site-packages/TurboCheetah-1.0-py2.5.egg', '/usr/lib64/
python2.5/site-packages/simplejson-1.8.1-py2.5-linux-x86_64.egg', '/
usr/lib64/python2.5/site-packages/RuleDispatch-0.5a0.dev_r2306-py2.5-
linux-x86_64.egg', '/usr/lib64/python2.5/site-packages/
PasteScript-1.6.2-py2.5.egg', '/usr/lib64/python2.5/site-packages/
FormEncode-1.0.1-py2.5.egg', '/usr/lib64/python2.5/site-packages/
DecoratorTools-1.7-py2.5.egg', '/usr/lib64/python2.5/site-packages/
configobj-4.5.2-py2.5.egg', '/usr/lib64/python2.5/site-packages/
CherryPy-2.3.0-py2.5.egg', '/usr/lib64/python2.5/site-packages/
kid-0.9.6-py2.5.egg', '/usr/lib64/python2.5/site-packages/
Cheetah-2.0.1-py2.5-linux-x86_64.egg', '/usr/lib64/python2.5/site-
packages/PyProtocols-1.0a0dev_r2302-py2.5-linux-x86_64.egg', '/usr/
lib64/python2.5/site-packages/PasteDeploy-1.3.1-py2.5.egg', '/usr/
lib64/python2.5/site-packages/Paste-1.6-py2.5.egg', '/usr/local/lib64/
python2.5/site-packages/pagedemo1-1.0-py2.5.egg', '/usr/lib/
python25.zip', '/usr/lib64/python2.5', '/usr/lib64/python2.5/plat-
linux2', '/usr/lib64/python2.5/lib-tk', '/usr/lib64/python2.5/lib-
dynload', '/usr/lib64/python2.5/site-packages', '/usr/lib64/python2.5/
site-packages/Numeric', '/usr/lib64/python2.5/site-packages/PIL', '/
usr/lib64/python2.5/site-packages/gtk-2.0', '/usr/lib64/python2.5/site-
packages/wx-2.8-gtk2-unicode', '/usr/local/lib64/python2.5/site-
packages']
>>>

Regards

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


Re: import cherrypy2

2008-06-06 Thread Chris
On Jun 6, 10:59 am, luca72 <[EMAIL PROTECTED]> wrote:
> On 6 Giu, 10:31, Chris <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Jun 6, 10:22 am, luca72 <[EMAIL PROTECTED]> wrote:
>
> > > Hello i can't import cherrypy2 but i don't know why this is the sys
> > > path:
>
> > > '', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
> > > setuptools-0.6c7-py2.5.egg', '/home/pirataja/opo.net/python/lib/
> > > python2.5/site-packages/TurboGears-1.0.4.4-py2.5.egg', '/home/pirataja/
> > > opo.net/python/lib/python2.5/site-packages/TurboKid-1.0.4-py2.5.egg',
> > > '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
> > > TurboJson-1.1.2-py2.5.egg', '/home/pirataja/opo.net/python/lib/
> > > python2.5/site-packages/TurboCheetah-1.0-py2.5.egg', '/home/pirataja/
> > > opo.net/python/lib/python2.5/site-packages/simplejson-1.9.1-py2.5-
> > > linux-i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-
> > > packages/RuleDispatch-0.5a0.dev_r2306-py2.5-linux-i686.egg', '/home/
> > > pirataja/opo.net/python/lib/python2.5/site-packages/PasteScript-1.6.2-
> > > py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
> > > FormEncode-1.0.1-py2.5.egg', '/home/pirataja/opo.net/python/lib/
> > > python2.5/site-packages/DecoratorTools-1.7-py2.5.egg', '/home/pirataja/
> > > opo.net/python/lib/python2.5/site-packages/configobj-4.5.2-py2.5.egg',
> > > '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
> > > CherryPy-2.3.0-py2.5.egg', '/home/pirataja/opo.net/python/lib/
> > > python2.5/site-packages/kid-0.9.6-py2.5.egg', '/home/pirataja/opo.net/
> > > python/lib/python2.5/site-packages/Cheetah-2.0.1-py2.5-linux-
> > > i686.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
> > > PyProtocols-1.0a0dev_r2302-py2.5-linux-i686.egg', '/home/pirataja/
> > > opo.net/python/lib/python2.5/site-packages/PasteDeploy-1.3.1-
> > > py2.5.egg', '/home/pirataja/opo.net/python/lib/python2.5/site-packages/
> > > Paste-1.7-py2.5.egg', '/home/pirataja/opo.net/python/lib/
> > > python25.zip', '/home/pirataja/pirata-jacopo.net/python/lib/
> > > python2.5', '/home/pirataja/opo.net/python/lib/python2.5/plat-
> > > linux2',
> > > '/home/pirataja/opo.net/python/lib/python2.5/lib-tk',
> > > '/home/pirataja/opo.net/python/lib/python2.5/lib-dynload', '/home/
> > > pirataja/opo.net/python/lib/python2.5/site-packages']
>
> > > For my is all ok but whe i do import cherrypy2 i get no mudule name
> > > cherrypy2
>
> > > Regards
>
> > > Luca
>
> > because it's "import cherrypy" and not "import cherrypy2"
>
> sorry but from another python installation i import cherrypy2 as
> cherrypy and all works
>
> Regards
>
> Luca

Did you install Lino on the other installation ?
http://lino.sourceforge.net/src/3.html
It's the only mention of a cherrypy2 I know of.
--
http://mail.python.org/mailman/listinfo/python-list


Re: ClassName.attribute vs self.__class__.attribute

2008-06-06 Thread Gabriel Rossetti

Larry Bates wrote:

Gabriel Rossetti wrote:

Hello everyone,

I had read somewhere that it is preferred to use 
self.__class__.attribute over ClassName.attribute to access class 
(aka static) attributes. I had done this and it seamed to work, until 
I subclassed a class using this technique and from there on things 
started screwing up. I finally tracked it down to 
self.__class__.attribute! What was happening is that the child 
classes each over-rode the class attribute at their level, and the 
parent's was never set, so while I was thinking that I had indeed a 
class attribute set in the parent, it was the child's that was set, 
and every child had it's own instance! Since it was a locking 
mechanism, lots of fun to debug... So, I suggest never using 
self.__class__.attribute, unless you don't mind it's children 
overriding it, but if you want a truly top-level class attribute, use 
ClassName.attribute everywhere!


I wish books and tutorials mentioned this explicitly

Gabriel


If you define a class instance variable with the same name as the 
class attribute, how would Python be able to distinguish the two?  
That is a feature not a problem.  Getter looks for instance attribute, 
if one is not found it looks for a class attribute, and upwards.  This 
behavior is used by Zope to do all sorts of neat stuff.


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


A class instance variable, you must mean an instance attribute no? If 
that is so, then with just self.attribute? Maybe there is a concept that 
I don't know about, I've studied class/static attributes and instance 
attributes in my OOP classes.


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


How to kill a thread?

2008-06-06 Thread John Dohn
Hi there,

How can I kill a threading.Thread subclass from MainThread?

My threads are waiting for data in Queue.get() method:
class MyThread(threading.Thread):
def run(self):
while True:
data = queue.get()# <- here it waits most of the time
... process data

>From the main thread I start several working threads:
thr = MyThread()
thr.start()
... feed the queue
and at the end for each thread I'd like to do something like thr.kill() or
thr.stop() or thr.destroy() or ... you got the point. I can't figure out
how.

Is there a way to do it?

Thanks!

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

Re: Convert Word .doc to Acrobat .pdf files

2008-06-06 Thread Paul Scott

On Fri, 2008-06-06 at 16:22 +0530, Dinil Karun wrote:
> hi,
> 
> I am using the below code but i am getting a error saying pyUno module
> not found.
> can u please help.

I just wrote the same thing!

Take a look at http://cvs2.uwc.ac.za/trac/python_tools/browser/oooconv

It should do what you want (and a little more).

Sorry, the code quality is pretty bad, but I am in the process of
cleaning it up still.

--Paul

All Email originating from UWC is covered by disclaimer 
http://www.uwc.ac.za/portal/public/portal_services/disclaimer.htm 
--
http://mail.python.org/mailman/listinfo/python-list

creating yaml without tags using pyyaml

2008-06-06 Thread Stephen Moore
hello

I have a situation where I have quite a large python object which I
want to convert to yaml so I can then send it to a flex application
using pyamf.

I've managed to create a yaml document using the python object
(http://flashbsm.googlecode.com/svn/testing/yamlTest/tester.yaml)
(using pyyaml)

however when I send the result of decoding the python object to yaml
to the flex app, the flex app complains about expecting a block end,
but not getting one.

I have come to the conclusion that this is the fault of the tags (for
example, !!python/tuple) as getting rid of them gets rid of the
errors.

So I'm wondering if there is an option to YAML.decode that will create
a yaml document without the tags?

Thankyou

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


Re: How to kill a thread?

2008-06-06 Thread Gerhard Häring

John Dohn wrote:

Hi there,

How can I kill a threading.Thread subclass from MainThread?

My threads are waiting for data in Queue.get() method:
class MyThread(threading.Thread):
def run(self):
while True:
data = queue.get()# <- here it waits most of the time
... process data

 From the main thread I start several working threads:
thr = MyThread()
thr.start()
... feed the queue
and at the end for each thread I'd like to do something like thr.kill() 
or thr.stop() or thr.destroy() or ... you got the point. I can't figure 
out how.


Is there a way to do it?


When I do this, I put a special value in the queue (like None) and in 
the worker thread, check for the special value and exit if found.


Threads can also be marked as "daemon threads" (see docs for 
threading.Thread objects). This will make the application terminate if 
only "daemon threads" are left.


So best would probably be soemthing like

- call setDaemon() when creating worker threads
- ...
- send all worker/daemon threads None via queue
- wait some time, like time.sleep(1.0), to let daemon exit themselves
- exit main application

-- Gerhard

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


Re: How to kill a thread?

2008-06-06 Thread John Dohn
On Fri, Jun 6, 2008 at 10:30 PM, John Dohn <[EMAIL PROTECTED]> wrote:

> Hi there,
>
> How can I kill a threading.Thread subclass from MainThread?


At the end I did:

def run(self):
while True:
if exit_event.isSet():
# Thread exiting
return
try:
data = q_in.get(timeout = .5)
except Queue.Empty:
continue
# ... process data

And then in the MainThread I do exit_event.set() and wait for all threads to
exit. It's a pretty awkward solution but works.

BTW Guys, is something like Thread.kill() planned for the future? Or is
there a reason not to have it?

Thanks

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

Re: creating yaml without tags using pyyaml

2008-06-06 Thread Kirill Simonov

Stephen Moore wrote:

I have come to the conclusion that this is the fault of the tags (for
example, !!python/tuple) as getting rid of them gets rid of the
errors.

So I'm wondering if there is an option to YAML.decode that will create
a yaml document without the tags?


Try yaml.safe_dump().

>>> import yaml

>>> print yaml.dump(())
!!python/tuple []

>>> print yaml.safe_dump(())
[]


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


BZip2 decompression and parsing XML

2008-06-06 Thread phasma
Hi.

I'm trying to disassemble bzipped file. If I use minidom.parseString,
I'm getting this error:

Traceback (most recent call last):
  File "./replications.py", line 342, in ?

  File "/usr/lib64/python2.4/xml/dom/minidom.py", line 1925, in
parseString
return expatbuilder.parseString(string)
  File "/usr/lib64/python2.4/xml/dom/expatbuilder.py", line 940, in
parseString
return builder.parseString(string)
  File "/usr/lib64/python2.4/xml/dom/expatbuilder.py", line 223, in
parseString
parser.Parse(string, True)
xml.parsers.expat.ExpatError: not well-formed (invalid token): line
538676, column 17

If I use minidom.parse, I'm getting this error:

Traceback (most recent call last):
  File "./replications.py", line 341, in ?
files.xml = minidom.parse(bz2.decompress(dump))
  File "/usr/lib64/python2.4/xml/dom/minidom.py", line 1915, in parse
return expatbuilder.parse(file)
  File "/usr/lib64/python2.4/xml/dom/expatbuilder.py", line 922, in
parse
fp = open(file, 'rb')
IOError

But XML parsed normally.

Code:

try:
handler = open(args[0], "r")
dump = handler.read()
handler.close()
except IOError, error:
print("Can't open dump: %s" % error)
sys.exit(1)

files.xml = minidom.parse(bz2.decompress(dump))

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


Re: BZip2 decompression and parsing XML

2008-06-06 Thread Stefan Behnel
phasma wrote:
> xml.parsers.expat.ExpatError: not well-formed (invalid token): line
> 538676, column 17

Looks like your XML file is broken in line 538676.


> try:
> handler = open(args[0], "r")

This should read

  handler = open(args[0], "rb")

Maybe that's your problem.

BTW, since you seem to parse a pretty big chunk of XML there, you should
consider using lxml. It's faster, more memory friendly, more feature-rich and
easier to use than minidom. It can also parse directly from a gzip-ed file or
a file-like object as provided by the bz2 module.

http://codespeak.net/lxml/

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


Re: Python CGI Upload from Server Status

2008-06-06 Thread John Dohn
On Sat, Jun 7, 2008 at 12:50 AM, Derek Tracy <[EMAIL PROTECTED]> wrote:

> I am trying to create a simple python cgi app that allows the user to kick
> off an ftp from the server the cgi is on to another server; I have that
> piece working using ftplib but since the files in question are usually very
> large (500mb to 2gb) in size I want to be able to display some sort of
> status to the user, preferrably a progress bar of some sort.


You'll need some AJAX progress bar (hint: google for this term ;-) that will
be getting updates from the server or request an update every second or so.

The question is if your upload code can provide progress tracking? If it's
just a call to some xyz.upload("/here/is/my-500M-file.bin") that only
returns after several minutes of uploading without giving you any updates on
how fast things go you're probably out of luck.
OTOH if it can do e.g.callbacks for progress reporting or if it can run in a
separate thread that you could query somehow you can hook that to that AJAX
thing of your choice.

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

Re: Python CGI Upload from Server Status

2008-06-06 Thread Derek Tracy
On Fri, Jun 6, 2008 at 9:16 AM, John Dohn <[EMAIL PROTECTED]> wrote:

> On Sat, Jun 7, 2008 at 12:50 AM, Derek Tracy <[EMAIL PROTECTED]> wrote:
>
>> I am trying to create a simple python cgi app that allows the user to kick
>> off an ftp from the server the cgi is on to another server; I have that
>> piece working using ftplib but since the files in question are usually very
>> large (500mb to 2gb) in size I want to be able to display some sort of
>> status to the user, preferrably a progress bar of some sort.
>
>
> You'll need some AJAX progress bar (hint: google for this term ;-) that
> will be getting updates from the server or request an update every second or
> so.
>
> The question is if your upload code can provide progress tracking? If it's
> just a call to some xyz.upload("/here/is/my-500M-file.bin") that only
> returns after several minutes of uploading without giving you any updates on
> how fast things go you're probably out of luck.
> OTOH if it can do e.g.callbacks for progress reporting or if it can run in
> a separate thread that you could query somehow you can hook that to that
> AJAX thing of your choice.
>
> JDJ
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I will look for the AJAX Progress Bar, but I will admit I have never touched
AJAX and haven't written javascript in years.

I patched Pythons ftplib.py storbinary() to send callbacks to the specified
method, so I have the callbacks locked down.  The thing to note is that this
app isn't allowing the user to upload to the server the cgi is on but rather
allowing the user to kick off an ftp process on the server to another
server.

Would there be a way to do this with python cgi and automatically append or
update information on the page it is displaying?

-- 
-
Derek Tracy
[EMAIL PROTECTED]
-
--
http://mail.python.org/mailman/listinfo/python-list

Re: configure fails

2008-06-06 Thread A.T.Hofkamp
On 2008-06-05, Mathieu Prevot <[EMAIL PROTECTED]> wrote:
> I have the following error on a OSX.5 OS with CC=icc and using the
> python-svn files:
>
> checking size of wchar_t... configure: error: cannot compute sizeof (wchar_t)
>
> I would like to help so we can compile python with icc/OSX.

This looks like a autoconf bug (./configure is normally created by autoconf)
.
You should check whether this wchar_t configure computation is part of the
standard autoconf macro's or a Python-project specific autoconf macro.

Then fix the problem and supply a patch to the right community.

You may want to subscribe to some autoconf mailing list

Sincerely,
Albert

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


cgi, parse_header and semi-colon

2008-06-06 Thread Sylvain
Hi,

I'm playing with Google App Engine and during my tests it seems that
there is a bug in cgi. parse_header function.

If we upload a file with a semi-colon (i.e : "C:/my;file.jpg") :
cgi.FieldStorage.filename returns only "my" everything after the semi-
colon is missing

Is it a bug or i'm missing something ?

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


Re: How to kill a thread?

2008-06-06 Thread Laszlo Nagy




def run(self):
while True:
if exit_event.isSet():
# Thread exiting
return
try:
data = q_in.get(timeout = .5)
except Queue.Empty:
continue
# ... process data
 
And then in the MainThread I do exit_event.set() and wait for all 
threads to exit. It's a pretty awkward solution but works.


BTW Guys, is something like Thread.kill() planned for the future? Or 
is there a reason not to have it?
Python threads are cooperative. I think there was a discussion about 
this, about a year ago or so. The answer was that in CPython, the 
interpreter has this GIL. Python threads are always running on the same 
processor, but they are not "native". There are operating system 
functions to kill a thread but you must not use them because it can 
crash the interpreter. Python MUST clean up object reference counts, 
manage memory etc. The OS function would kill the thread in a way so 
that it would be impossible to fee up memory, and also the interpreter 
can be left in bad state.


I'm not sure about the details, but the short answer is that it is not 
planned. Many programmers said that you have to write cooperative 
threads anyway. Killing threads forcedly is not a good idea in any language.


I hope others will correct me if I'm wrong.

Best,

  Laszlo

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


Re: creating yaml without tags using pyyaml

2008-06-06 Thread Stephen Moore
On Fri, Jun 6, 2008 at 8:20 PM, Kirill Simonov <[EMAIL PROTECTED]> wrote:
> Stephen Moore wrote:
>>
>> I have come to the conclusion that this is the fault of the tags (for
>> example, !!python/tuple) as getting rid of them gets rid of the
>> errors.
>>
>> So I'm wondering if there is an option to YAML.decode that will create
>> a yaml document without the tags?
>
> Try yaml.safe_dump().
>
 import yaml
>
 print yaml.dump(())
> !!python/tuple []
>
 print yaml.safe_dump(())
> []
>
>
> Thanks,
> Kirill
>

yes, that's exactly what I wanted :)

however it still caused problems...

but I've managed to make it so it doesn't use tuples and now it all
seems to work.

thankyou for your help anyways, it's greatly appreciated :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Proof that \ is a better line joiner than parenthetical sets

2008-06-06 Thread Jordan Greenberg

Joshua Kugler wrote:

"Beautiful is better than ugly."
And I think putting parenthesis around a multi-line statement is much
prettier.

So there! :)

j


And PEP 8 agrees with you. Another vote for parens.

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


Re: Partial download with ftplib and retrbinary

2008-06-06 Thread Giampaolo Rodola'
On 24 Mag, 12:53, [EMAIL PROTECTED] wrote:
> I am breaking/interrupting my connection with theftpserver at
> present when doing a partial download of a file. I have a callback
> with retrbinary that raises an exception and ends the download. The
> problem is that the server is not notified and hangs. I cannot send
> any further commands and need to relogin to download further. Is there
> a way to still continue downloading without having to login again.
>
> My retrbinary function is:
>
> ftp.retrbinary('RETR '+file, handleDownload,1,bound[0])
>
> where bound[0] is an integer specifying the start byte of the
> download.
>
> My callback is:
>
> def handleDownload(block):
>     global count,localfile,number
>     localfile.write(block)
>     if count==number:
>             raise(Exception)
>     count=count+1
>
> where number specifies the number of bytes to download.
>
> Help would be gratefully received.

The server hangs on because the data connection is left open.
Unfortunately you have no easy way to close the data connection by
using retrbinary.
You have to trick a little bit and keep a reference of the data socket
and manually close it.
The example below starts to retrieve a file and stops when 524288
bytes have been received.
Hope this could help you.


import ftplib
ftp = ftplib.FTP('127.0.0.1', 'user', 'password')
ftp.voidcmd('TYPE I')
conn = ftp.transfercmd('RETR filename') # the data socket
bytes_recv = 0
while 1:
chunk = conn.recv(8192)
# stop transfer while it isn't finished yet
if bytes_recv >= 524288: # 2^19
break
elif not chunk:
break
file.write(chunk)
bytes_recv += len(chunk)
conn.close()


--- Giampaolo
http://code.google.com/p/pyftpdlib
--
http://mail.python.org/mailman/listinfo/python-list


Re: ClassName.attribute vs self.__class__.attribute

2008-06-06 Thread Bruno Desthuilliers

Hrvoje Niksic a écrit :

"[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
writes:


On 5 juin, 17:40, Gabriel Rossetti <[EMAIL PROTECTED]>
wrote:

Hello everyone,

I had read somewhere that it is preferred to use
self.__class__.attribute over ClassName.attribute to access class (aka
static) attributes.

It's even prefered to use self.attribute,


I was going to write exactly that, but it occurred to me that he might
want to be *assigning* to self.__class__.attribute (or
HisClass.attribute) from his methods, in which case self.attribute
would be quite different.


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


Re: ClassName.attribute vs self.__class__.attribute

2008-06-06 Thread Bruno Desthuilliers

Gabriel Rossetti a écrit :

Larry Bates wrote:

Gabriel Rossetti wrote:

Hello everyone,

I had read somewhere that it is preferred to use 
self.__class__.attribute over ClassName.attribute to access class 
(aka static) attributes. I had done this and it seamed to work, until 
I subclassed a class using this technique and from there on things 
started screwing up. I finally tracked it down to 
self.__class__.attribute! What was happening is that the child 
classes each over-rode the class attribute at their level, and the 
parent's was never set, so while I was thinking that I had indeed a 
class attribute set in the parent, it was the child's that was set, 
and every child had it's own instance! Since it was a locking 
mechanism, lots of fun to debug... So, I suggest never using 
self.__class__.attribute, unless you don't mind it's children 
overriding it, but if you want a truly top-level class attribute, use 
ClassName.attribute everywhere!


I wish books and tutorials mentioned this explicitly

Gabriel


If you define a class instance variable with the same name as the 
class attribute, how would Python be able to distinguish the two?  
That is a feature not a problem.  Getter looks for instance attribute, 
if one is not found it looks for a class attribute, and upwards.  This 
behavior is used by Zope to do all sorts of neat stuff.


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


A class instance variable, you must mean an instance attribute no? 


I think that's what he meant, yes.

If 
that is so, then with just self.attribute? Maybe there is a concept that 
I don't know about, 


The concept of name resolution (aka lookup) rules in Python, perhaps ? 
When you do obj.attribute, attribute is first looked for in the object, 
then in it's class, then in the parent classes. So yes, you can get a 
class (or parent class) attribute directly on the instance. Note that 
assignment on the instance (obj.attribute = value) will alway (computed 
attributes or other hooks excepted) create the attribute on the target, 
so if you have Class.attribute set, and then do obj = Class(); 
obj.attribute = 42, then obj.attribute will shadow Class.attribute.


I've studied class/static attributes and instance 
attributes in my OOP classes.


Forget about your OOP classes, mostly if it was in fact a Java or C++ 
class. Python's object model is very far away from what most courses 
present as "OOP".



Gabriel

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


Re: Why does python not have a mechanism for data hiding?

2008-06-06 Thread Bruno Desthuilliers

Russ P. a écrit :

On Jun 4, 4:29 am, NickC <[EMAIL PROTECTED]> wrote:

On Jun 4, 4:09 am, "Russ P." <[EMAIL PROTECTED]> wrote:


What is it about leading underscores that bothers me? To me, they are
like a small pebble in your shoe while you are on a hike. Yes, you can
live with it, and it does no harm, but you still want to get rid of it.

With leading underscores, you can see *at the point of dereference*
that the code is accessing private data. With a "this is private"
keyword you have no idea whether you're accessing private or public
data, because the two namespaces get conflated together.


That is true. But with the "priv" keyword you'll discover quickly
enough that you are trying to access private data (as soon as you run
the program).


With the current convention, you don't even have to run the program - as 
soon as you *type* the name, you know you're accessing implementation stuff.



And even if a "priv" keyword is added, you are still
free to use the leading underscore convention if you wish.


What does this "priv keyword" buy you then ? Seriously ?


The idea of being able to discern properties of an object by its name
alone is something that is not normally done in programming in
general. 


Want to talk about the hungarian notation that is everywhere in MS 
Windows code ?-) or about the so common C++ coding guideline that 
insists on prefixing "data members" with a m_ or a w_ ?-)


More seriously: yes, you usually try to convey something about some 
relevant properties of the object in the identifier. Like, you know, 
using plurals for collections. Or i, j as loop indices.



Yes, of course you should choose identifiers to be
descriptive of what they represent in the real world, but you don't
use names like "intCount," "floatWeight," or "MyClassMyObject" would
you? 


Nope.


Why not?


Because the naming convention for variables is all_lower_with_underscores.

Also, because 'count' is likely enough to be an integer and 'weight' 
likely enough to be a float - and else another numeric. While 'counts' 
and 'weights' are likely enough to be collections (likely lists) of 
resp. integers and floats.

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


File-writing not working in Windows?

2008-06-06 Thread tdahsu
All,

I have the following code:
   for fileTarget in dircache.listdir("directory"):
(dirName, fileName) = os.path.split(fileTarget)
f = open(fileTarget).readlines()
copying = False
for i in range(len(f)):
for x in range (0,24,1):
if (re.search(self.Info[x][3], f[i])):
#If we have a match for our start of section...
if (self.Info[x][2] == True):
#And it's a section we care about...
copying =
True  #Let's start copying the lines out
to the temporary file...
if (os.name == "posix"):
if (self.checkbox25.GetValue() ==
False):
tempfileName = "tempdir/" +
self.Info[x][0] + "_tmp_" + fileName + ".txt"
else:
tempfileName =
self.textctrl07.GetValue() + "/" + self.Info[x][0] + "_xyz.txt"
else:
if (self.checkbox25.GetValue() ==
False):
tempfileName = "tempdir\\" +
self.Info[x][0] + "_tmp_" + fileName + ".txt"
else:
tempfileName =
self.textctrl07.GetValue() + "\\" + self.Info[x][0] + "_xyz.txt"
else:
copying = False
if (re.search(self.Info[x][4], f[i])):
#Now we've matched the end of our section...
copying =
False #So let's stop copying out to
the temporary file...
if (copying == True):
g = open(tempfileName,
'a') #Open that file in append mode...
 
g.write(f[i])   #Write the line...
g.close()

This code works PERFECTLY in Linux.  Where I have a match in the file
I'm processing, it gets cut out from the start of the match until the
end of the match, and written to the temporary file in tempdir.

It does not work in Windows.  It does not create or write to the
temporary file AT ALL.  It creates the tempdir directory with no
problem.

Here's the kicker: it works perfectly in Windows if Windows is running
in VMware on a Linux host!  (I assume that that's because VMware is
passing some call to the host.)

Can anyone tell me what it is that I'm missing which would prevent the
file from being created on Windows natively?

I'm sorry I can't provide any more of the code, and I know that that
will hamper your efforts in helping me, so I apologise up front.

Assumptions:
You can assume self.checkbox25.GetValue() is always false for now, and
self.Info[x][0] contains a two character string like "00" or "09" or
"14".  There is always a match in the fileTarget, so self.Info[x][2]
will always be true at some point, as will self.Info[x][4].  I am
cutting an HTML file at predetermined comment sections, and I have
control over the HTML files that are being cut.  (So I can force the
file to match what I need it to match if necessary.)

I hope however that it's something obvious that a Python guru here
will be able to spot and that this n00b is missing!

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


Re: Why does python not have a mechanism for data hiding?

2008-06-06 Thread Bruno Desthuilliers

Russ P. a écrit :

On Jun 5, 4:53 am, Bruno Desthuilliers  wrote:

Russ P. a écrit :



Given your very recent discovery of what 'dynamic' *really* means in
Python (like, for exemple, dynamically adding / replacing attributes -
including methods - on a per-class or per-instance basis), possibly, yes.


My "very recent" discovery? Funny, I thought I knew that several years
ago. 


Looks like I mistook your
"""
I also realize, by the way, that Python allows a client of a class to
define a new class member from completely outside the class
definition
"""

as "I just realized (...)"

Sorry for having read too fast.


I also realize, by the way, that Python allows a client of a class to
define a new class member from completely outside the class
definition. Obviously, that cannot be declared private.

Why so ?


Why should the client of a class not be able to declare a *private*
member of the class? You're kidding, right?


I'm dead serious. I often add implementation attributes to either a 
class or an instance. These *are* implementation parts, not API.



Do you mind if I tell you
how to arrange the furniture in your bedroom?


I must be a bit dumb, but I don't see how human interaction problems 
relate to enforced access restriction in an OO programming language.



But if the
same identifier is already declared private within the class, than the
new definition should not be allowed (because it would defeat the
whole idea of "private" class members).

Why so ?

Metaprogramming (including monkeypatching) is part of the pythoneer's
toolbox, and while it's not something to use without pretty good
reasons, it has many times proven to be a real life saver. In languages
not allowing it, the solutions to the class of problems easily solved by
monkeypatching happens to be at best a kludge, at worst plain
unsolvable, at least without too much effort to be even worth it. Your
above proposition would arbitrarily make possible and useful things
either uselessly complicated or near impossible.


For the record, I have made it abundantly clear that I don't think
Python should not have as rigorous an encapsulation regime as C++ or
Java. The worst that could happen with my proposition is that you
would need to use a "mangled" name to access private data or methods.


That's already the case - when you use __name_mangling. And if there's 
no effective access restriction, then what the point of having this 
'priv' keyword ?



But you will be using the name many times, you can reassign your own
name, of course, so the mangled name need not appear more than once
where it is needed.


Once again, I just don't see the point. Either you want effective access 
restriction in Python, or you don't. And if you don't, what would this 
'priv' keyword be useful to ?

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


Re: parser recommendation

2008-06-06 Thread Kay Schluehr
On 6 Jun., 01:58, Alan Isaac <[EMAIL PROTECTED]> wrote:
> One other possibility:
> SimpleParse (for speed).
> http://simpleparse.sourceforge.net/>
> It is very nice.
> Alan Isaac

How does SimpleParse manage left-factorings, left-recursion and other
ambiguities?

For example according to [1] there are two non-terminals

UNICODEESCAPEDCHAR_16

and

UNICODEESCAPEDCHAR_32

with an equal initial section of 4 token. How does SimpleParse detect
when it has to use the second production?

[1] http://simpleparse.sourceforge.net/simpleparse_grammars.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why does python not have a mechanism for data hiding?

2008-06-06 Thread Bruno Desthuilliers

Russ P. a écrit :

On Jun 5, 2:27 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:

On Thu, 5 Jun 2008 11:36:28 -0700 (PDT), "Russ P."
<[EMAIL PROTECTED]> declaimed the following in comp.lang.python:


would need to use a "mangled" name to access private data or methods.
But you will be using the name many times, you can reassign your own
name, of course, so the mangled name need not appear more than once
where it is needed.

Which will break the first time the "innards" rebind a value to the
mangled name, as the "simplified" external name will still be bound to
the previous value.


I'm not sure you understood what I meant. In current Python, if I need
access to data element __XX in class YourClass, I can use
ZZ._YourClass__XX, but if I don't want to clutter my code with that
mangled name, I can just write

XX = ZZ._YourClass__XX

and refer to it from that point on as XX. 

>

Obviously if the meaning of
__XX changes within class ZZ, this will break, but that's why you are
supposed to avoid using private data in the first place.


AFAICT, What Dennis meant is that the binding of ZZ._YourClass__XX 
changes between the moment you bind it to local XX and the moment you 
use it, then you're out.

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


Re: Newb question: underscore

2008-06-06 Thread Bruno Desthuilliers

[EMAIL PROTECTED] a écrit :

My question is: Why would anyone decide to obfuscate something as easy
to read as Python???

They didn't decide to obfuscate; they decided to follow a
strongly-expected convention for the name of that function by existing
users of the 'gettext' functionality, in contexts that predate the
appearance of that functionality in Python.



Well _ can also mean the previous output statement that wasn't null,


In the shell only IIRC.

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


Re: Newb question: underscore

2008-06-06 Thread Bruno Desthuilliers

John Fabiani a écrit :

Skye wrote:


What is this doing?

print >> fd, _(__doc__)


I'm guessing line-splitting __doc__ into a list, but what's that
leading underscore do?

Thanks!

I think it is standard practice to use the underscore for unicode converts.


Actually, it's for i18n, not for encoding.
--
http://mail.python.org/mailman/listinfo/python-list


Re: cgi, parse_header and semi-colon

2008-06-06 Thread Richard Brodie

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

> If we upload a file with a semi-colon (i.e : "C:/my;file.jpg") :
> cgi.FieldStorage.filename returns only "my" everything after the semi-
> colon is missing
>
> Is it a bug or i'm missing something ?

I doubt it's bug in parse_header, since it's meant to split on
semicolons. Whether it's a bug in one of its callers, or the client
not escaping sufficiently, I couldn't say offhand.


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


Re: File-writing not working in Windows?

2008-06-06 Thread jay graves
On Jun 6, 10:18 am, [EMAIL PROTECTED] wrote:

> This code works PERFECTLY in Linux.  Where I have a match in the file
> I'm processing, it gets cut out from the start of the match until the
> end of the match, and written to the temporary file in tempdir.
> It does not work in Windows.  It does not create or write to the
> temporary file AT ALL.  It creates the tempdir directory with no
> problem.

In general, I don't use string concatenation when building paths.
Especially on scripts that are meant to run on multiple platforms.


> Here's the kicker: it works perfectly in Windows if Windows is running
> in VMware on a Linux host!  (I assume that that's because VMware is
> passing some call to the host.)

probably a red herring.

> Can anyone tell me what it is that I'm missing which would prevent the
> file from being created on Windows natively?

Get rid of the 'posix' check and use os.path.join to create
'tempfileName' and see if it works.

HTH.
...
Jay Graves
--
http://mail.python.org/mailman/listinfo/python-list


How to remove read-only from a file

2008-06-06 Thread Robert Dailey
Hi,

Using Python 3.0, how can I remove a read-only property from a file in
Windows XP? Thanks.
--
http://mail.python.org/mailman/listinfo/python-list

Re: How to remove read-only from a file

2008-06-06 Thread Tim Golden

Robert Dailey wrote:

Hi,

Using Python 3.0, how can I remove a read-only property from a file in
Windows XP? Thanks.


import os
import stat

os.chmod ("c:/temp/temp.txt", stat.S_IWRITE)

(Haven't actually checked that on Python 3.0 but I don't believe
it's changed...)

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


Re: Image Processing (batch)

2008-06-06 Thread Ivan Illarionov
On Thu, 05 Jun 2008 07:10:56 +, Tim Roberts wrote:

> Thomas Guettler <[EMAIL PROTECTED]> wrote:
>>
>>I tried PIL for image batch processing. But somehow I don't like it
>>  - Font-Selection: You need to give the name of the font file. -
>>  Drawing on an image needs a different object that pasting and saving.
>>  - The handbook is from Dec. 2006.

I don't want to dissapoint you but PIL font handling sucks terribly.

> I have repeatedly seen the attitude in your last point, and I simply do
> not understand it.  What on Earth is wrong with having a product that
> actually becomes stable?
> 
> We all complain about Microsoft's feature bloat, rolling out unnecessary
> new releases of their products year after year with features that no one
> really needs.  But when an open source product FAILS to produce a new
> release every six weeks, we start seeing posts questioning whether the
> product is still viable or has become abandonware.

I think if you really TRY to create your own project you'll understand 
what's going on here.

>From near 10 open source projects that I've started only 1 is living 
today.

> Once a product does the job it was designed to do, IT'S DONE.

Because there's no such thing as "do the job you where designed to do"
Example: designed for image manipulation. No matter how many features 
you've already implemented there's always something more to do.

> Personally, I think PIL is a great solution for batch processing, but
> the beauty of the open source world is that the ARE alternatives.

Yes, it's open source, and everybody will win if you'll extend PIL to do 
what you want.

Really, I do have some working snippets of code that do handle fonts 
nicely with PIL images, read and parse OpenType tables, but I can't 
publish it because it's optimized for my private needs like only two 
languages: Russian and English.

I had to rewrite PIL's FreeType layer from scratch to do what I want.

You can do the same.

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


Re: ClassName.attribute vs self.__class__.attribute

2008-06-06 Thread David C. Ullrich
In article <[EMAIL PROTECTED]>,
 Gabriel Rossetti <[EMAIL PROTECTED]> wrote:

> Larry Bates wrote:
> > Gabriel Rossetti wrote:
> >> Hello everyone,
> >>
> >> I had read somewhere that it is preferred to use 
> >> self.__class__.attribute over ClassName.attribute to access class 
> >> (aka static) attributes. I had done this and it seamed to work, until 
> >> I subclassed a class using this technique and from there on things 
> >> started screwing up. I finally tracked it down to 
> >> self.__class__.attribute! What was happening is that the child 
> >> classes each over-rode the class attribute at their level, and the 
> >> parent's was never set, so while I was thinking that I had indeed a 
> >> class attribute set in the parent, it was the child's that was set, 
> >> and every child had it's own instance! Since it was a locking 
> >> mechanism, lots of fun to debug... So, I suggest never using 
> >> self.__class__.attribute, unless you don't mind it's children 
> >> overriding it, but if you want a truly top-level class attribute, use 
> >> ClassName.attribute everywhere!

I shouldn't butt in since everyone else knows more about
this than I do, but it seems to me that saying you should
do this is wrong and saying you should do that is wrong -
which you should do depends on what you're trying to
accomplish.

There's something that comes up all the time in stuff
I do, where implicitly accessing self.__class__.attribute
is vital to make it work right. Say I have a Matrix class,
with an __add__ method:

class Matrix:
  def __init__(self, data):
whatever
  def __add__(self, other):
newdata = whatever
return Matrix(newdata)

The last line is almost surely not what I want (took
me a while, long ago, to figure this out). Because someday
when I have a subclass I want __add__ to return an instance
of the subclass. At first I thought I needed to rewrite the
last line to return SubClass(newdata). No, I simply return
self.__class__(newdata) and it works exactly the way I want.

> >> I wish books and tutorials mentioned this explicitly
> >>
> >> Gabriel
> >
> > If you define a class instance variable with the same name as the 
> > class attribute, how would Python be able to distinguish the two?  
> > That is a feature not a problem.  Getter looks for instance attribute, 
> > if one is not found it looks for a class attribute, and upwards.  This 
> > behavior is used by Zope to do all sorts of neat stuff.
> >
> > -Larry Bates
> > -- 
> > http://mail.python.org/mailman/listinfo/python-list
> >
> >
> A class instance variable, you must mean an instance attribute no? If 
> that is so, then with just self.attribute? Maybe there is a concept that 
> I don't know about, I've studied class/static attributes and instance 
> attributes in my OOP classes.
> 
> Gabriel

-- 
David C. Ullrich
--
http://mail.python.org/mailman/listinfo/python-list


SWIG -- Passing python proxy class instance to python callback

2008-06-06 Thread Keith Sabine

Hi

Did you ever find a solution to this? I am having the exact same problem...

- Keith

I'm trying to pass a proxy class instance (SWIG generated) of CClass,
to a python callback function from C++.  The proxy class instance of
CClass is created from a pointer to the C++ class CClass.

Using the code below, I receive the error message:

"AttributeError: 'PySwigObject' object has no attribute 'GetName'"


The python callback function is being passed in through the clientdata
pointer, and the CClass *class pointer is what's being converted to an
instance of the SWIG proxy class and passed to the python callback
function as an argument.

static void PythonCallBack(CClass *class,void *clientdata)
{
  PyObject *func, *arglist,*obj;
  PyObject *result;

  func = (PyObject *) clientdata;   // Get Python function
  obj = SWIG_NewPointerObj((void*) cmd, SWIGTYPE_p_CSCSICommand,  1);
//create instance of python proxy class from c++ pointer

  arglist=Py_BuildValue("(O)",*obj); //convert to tuple
  result = PyEval_CallObject(func,arglist); // Call Python

  Py_XDECREF(result);
  return;
}

Any input would greatly appreciated.  Thanks,
Jeff


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


lots of futex_wait calls

2008-06-06 Thread skunkwerk
I've got a python program written for the django web framework that
starts about 100 threads.  When I start the server, it sometimes eats
up 100% of the CPU for a good minute or so... though none of the
threads are CPU-intensive

doing a strace on the program, i found lots of calls like this:

select(5, [4], [], [], {1, 0}) = 0 (Timeout)
futex(0x86a3ce0, FUTEX_WAIT, 0, NULL) = 0

i've read the man page for futex... but is this normal?

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


Re: How to kill a thread?

2008-06-06 Thread Diez B. Roggisch

Laszlo Nagy schrieb:




def run(self):
while True:
if exit_event.isSet():
# Thread exiting
return
try:
data = q_in.get(timeout = .5)
except Queue.Empty:
continue
# ... process data
 
And then in the MainThread I do exit_event.set() and wait for all 
threads to exit. It's a pretty awkward solution but works.


BTW Guys, is something like Thread.kill() planned for the future? Or 
is there a reason not to have it?
Python threads are cooperative. I think there was a discussion about 
this, about a year ago or so. The answer was that in CPython, the 
interpreter has this GIL. Python threads are always running on the same 
processor, but they are not "native". There are operating system 
functions to kill a thread but you must not use them because it can 
crash the interpreter. 


This is not correct. Neither are threads cooperative nor are they not 
native. If they weren't cooperative they needed explicit re-scheduling 
statements in the code. And they also are based on native OS threads.


They might *appear* not cooperative if a long-running C-call doesn't 
release the GIL beforehand.


This of course doesn't affect other parts of your reasoning about 
killing threads being a bad idea and such.


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


The best sexy video and photo!!!

2008-06-06 Thread sexy18
http://rozrywka.yeba.pl/show.php?id=2737
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to remove read-only from a file

2008-06-06 Thread Robert Dailey
On Fri, Jun 6, 2008 at 11:05 AM, Tim Golden <[EMAIL PROTECTED]> wrote:

> Robert Dailey wrote:
>
>> Hi,
>>
>> Using Python 3.0, how can I remove a read-only property from a file in
>> Windows XP? Thanks.
>>
>
> import os
> import stat
>
> os.chmod ("c:/temp/temp.txt", stat.S_IWRITE)
>
> (Haven't actually checked that on Python 3.0 but I don't believe
> it's changed...)


Works great, thank you!
--
http://mail.python.org/mailman/listinfo/python-list

Re: lots of futex_wait calls

2008-06-06 Thread André Malo
skunkwerk wrote:

> I've got a python program written for the django web framework that
> starts about 100 threads.  When I start the server, it sometimes eats
> up 100% of the CPU for a good minute or so... though none of the
> threads are CPU-intensive
> 
> doing a strace on the program, i found lots of calls like this:
> 
> select(5, [4], [], [], {1, 0}) = 0 (Timeout)
> futex(0x86a3ce0, FUTEX_WAIT, 0, NULL) = 0
> 
> i've read the man page for futex... but is this normal?

More or less. Most of the futex calls (if not all) are grabbing or releasing
the global interpreter lock (GIL).

It's usually helpful to increase the thread-schedule-checkinterval in order
to lessen the system load (especially the number of context switches). See
sys.setcheckinterval.

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


ctypes help

2008-06-06 Thread gianluca
hy,
I've a huge problem with ctypes. I've compiled my C library and I'd
like use it in python with ctype. One function need to pass a pointer
to typed ( like this: typedef int value_type). In python I can access
to that funtion but arise an exception  because python don't know my
value_type typedef.

Please I need help, could anybody help me?

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


noob question : library versus normal python files

2008-06-06 Thread ravinder thakur
hello friends,


i have a python library(rdflib) that i am using in some project using
Google App Engine. I have developed everything using this on my local
machine and things work fine. But in my final deployment, i have to
use it in source code form rather than in library form. If i remove
the library and start using the source code, thing are just not
working even if i append the dir of source to the python path. any
ideas on how to use the source code for a python library rather than
using the library itself ?


i tried googling any good tutorial for python libraries but couldn't
find one. can someone share a link or something similar ?


thanks
ravinder thakur
--
http://mail.python.org/mailman/listinfo/python-list


Re: Do this as a list comprehension?

2008-06-06 Thread John Salerno
"Terry Reedy" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>
> "Mensanator" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]

> Which is exactly the purpose of zip, or its specialization enumerate!

Thanks guys! Looks like the simplest is always the best yet again! :) 


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


Where to find Visual Studio Syntax Highlighting (for python)?

2008-06-06 Thread Robert Dailey
Hi,

Does anyone know of a way to get syntax coloring working in Visual Studio
2008 for Python? I did some googling but I couldn't find anything. Help is
appreciated, thank you.
--
http://mail.python.org/mailman/listinfo/python-list

Re: Do this as a list comprehension?

2008-06-06 Thread Mensanator
On Jun 6, 1:44 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> "Mensanator" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
> | On Jun 5, 10:42?pm, John Salerno <[EMAIL PROTECTED]> wrote:
> | > Is it possible to write a list comprehension for this so as to produce
> a
> | > list of two-item tuples?
> | >
> | > base_scores = range(8, 19)
> | > score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3]
> | > print zip(base_scores, score_costs)
> | >
> | > I can't think of how the structure of the list comprehension would work
> | > in this case, because it seems to require iteration over two separate
> | > sequences to produce each item in the tuple.
>
> Which is exactly the purpose of zip, or its specialization enumerate!

Aren't you overlooking the fact that zip() truncates the output
to the shorter length iterable? And since the OP foolishly
hardcoded his range bounds, zip(base_scores,score_cost) will
silently return the wrong answer if the base_count list grows.

Surely enumerate() wasn't added to Python with no intention of
ever being used.


>
> | > zip seems to work fine anyway, but my immediate instinct was to try a
> | > list comprehension (until I couldn't figure out how!). And I wasn't
> sure
> | > if list comps were capable of doing everything a zip could do.
> |
> | base_scores = range(8, 19)
> | score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3]
> | print zip(base_scores, score_costs)
> |
> | s = [(i+8,j) for i,j in enumerate( [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3])]
> | print s
> |
> | ##>>>
> | ##[(8, 0), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15,
> | 2), (16, 2), (17, 3), (18, 3)]
> | ##[(8, 0), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15,
> | 2), (16, 2), (17, 3), (18, 3)]
> | ##>>>
>
> Of course, enumerate(iterable) is just a facade over zip(itertools.count(),
> iterable)

But if all I'm using itertools for is the count() function, why would
I
go to the trouble of importing it when I can simply use enumerate()?

Is it a couple orders of magnitude faster?

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


Assigning to __class__ : bad form?

2008-06-06 Thread The Pythonista
I've been wondering for a while about whether assigning to __class__ is 
bad form or not.  Specifically, I mean doing so when some other method of 
implementing the functionality you're after is available (i.e. using an 
adapter, or something like the strategy pattern).

To give an example and a non-example of what I'm talking about, consider 
the following recipes from the online Python Cookbook:

Ring Buffer: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68429

In this case, I think the assignment to __class__ just obfuscates things, 
and the example would be better coded as a single class.

On the other hand,

Fast copy of an object having a slow __init__ : http://
aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66507

This seems like a reasonable use case for assigning to __class__ (except 
that it's already implemented in the 'new' module, but, read the Martelli-
bot's comments near the end of the recipe).  I consider this a reasonable 
use case for assigning to __class__, because, short of the 'new' module, 
I don't see any other way to accomplish it.

So, what is the opinion of the broader Python community?  Is code that 
assigns to __class__ just clever trickiness to be avoided, or is it 
sometimes a good thing?

-- 
code.py: A blog about life, the universe, and Python

http://pythonista.wordpress.com
** Posted from http://www.teranews.com **
--
http://mail.python.org/mailman/listinfo/python-list


My company provide most popular of the shoes model, bag, clothes, Bikini swimwear, sunglasses and watch of etc..

2008-06-06 Thread hongfeng13
hello ! ! !welcome to visit our website  http://www.nikeadishoes.com
Our main products :  shoes Hoodies T-Shirt Jeans Jacket bags
Electronic and so on

we can supply many popular shoes model,bag,clothes ,bikini,sunglass
and watch and so on. We can give you products with good quality and
reasonable price! We are looking forward to do business with you. Do
not hesitate and contact with us!


[EMAIL PROTECTED]  products 100% authentic
MSN: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


My company provide most popular of the shoes model, bag, clothes, Bikini swimwear, sunglasses and watch of etc..

2008-06-06 Thread hongfeng13
hello ! ! !welcome to visit our website  http://www.nikeadishoes.com
Our main products :  shoes Hoodies T-Shirt Jeans Jacket bags
Electronic and so on

we can supply many popular shoes model,bag,clothes ,bikini,sunglass
and watch and so on. We can give you products with good quality and
reasonable price! We are looking forward to do business with you. Do
not hesitate and contact with us!


[EMAIL PROTECTED]  products 100% authentic
MSN: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: File-writing not working in Windows?

2008-06-06 Thread tdahsu
On Jun 6, 11:35 am, jay graves <[EMAIL PROTECTED]> wrote:
> On Jun 6, 10:18 am, [EMAIL PROTECTED] wrote:
> 
>
> > This code works PERFECTLY in Linux.  Where I have a match in the file
> > I'm processing, it gets cut out from the start of the match until the
> > end of the match, and written to the temporary file in tempdir.
> > It does not work in Windows.  It does not create or write to the
> > temporary file AT ALL.  It creates the tempdir directory with no
> > problem.
>
> In general, I don't use string concatenation when building paths.
> Especially on scripts that are meant to run on multiple platforms.
>
> > Here's the kicker: it works perfectly in Windows if Windows is running
> > in VMware on a Linux host!  (I assume that that's because VMware is
> > passing some call to the host.)
>
> probably a red herring.
>
> > Can anyone tell me what it is that I'm missing which would prevent the
> > file from being created on Windows natively?
>
> Get rid of the 'posix' check and use os.path.join to create
> 'tempfileName' and see if it works.
>
> HTH.
> ...
> Jay Graves

Jay,

Thank you for your answer.  I have researched os.path.join.  I have
changed the code to read as follows:

if (self.checkbox25.GetValue() == False):
initialFileName = self.Info[x][0] + "_tmp_" + fileName + ".txt"
tempfileName = os.path.join("proctemp", initialFileName)
else:
initialFileName = self.Info[x][0] + "_xyz.txt"
tempfileName = os.path.join("proctemp", initialFileName)

this still works in Linux; it does not work in Windows.

I am thinking that the "g.open(tempFileName, 'a')" command is the
issue.  Is there anything different about opening a file in Windows?
Does Windows understand "append", or would I have to do control checks
for seeing if the file is created and then appending?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cannot use Winpdb (or PyDev) to trace embedded Python script in MSVC++ application - ImportError: No module named _socket

2008-06-06 Thread Chris8Boyd
On Jun 6, 1:13 am, Nir <[EMAIL PROTECTED]> wrote:
> You seem to be having a problem with the import path of the embedded
> interpreter. I suppose the embedded interpreter includes some modules
> in a particular folder and _socket is not one of them. For the sake of
> debugging try adding the c:\python25\lib path to the sys.path variable
> of the interpreter before attempting to import rpdb2.
>
> Does this work?
>
> Nir
>
> On Jun 5, 2:52 pm, [EMAIL PROTECTED] wrote:
>
> > I am embedding Python in a MSVC++ (2005) application. The application
> > creates some environment and then launches a Python script that will
> > call some functions exported from the MSVC++ application.
>
> > I want to be able to debug the Python script by using a debug server,
> > likeWinpdb(winpdb.org).
>
> > I use ActivePython 2.5.2.2, Microsoft Visual Studio 2005, andWinpdb
> > 1.3.8.
>
> > When I launch a script like "e:>python test.py" everything is O'K and
> > I can useWinpdbto trace/debug.
>
> > When I run the same script from the MSVC++ application, there is
> > always a complain "ImportError: No module named _socket".
>
> > Here is the basic test script I use:
>
> > def Process( something ):
> > print "\n\nStarted debugging\n=\n"
> > #pydevd.settrace()
> > import rpdb2; rpdb2.start_embedded_debugger("1")
> > print "\n\nStopped debugging\n=\n"
>
> > if __name__ == '__main__':
> > Process( "test" )
> > <<<
>
> > In the MSVC++ application I tried many approaches, as suggested by
> > many people, and all of them work to launch the script, but none of
> > them works withWinpdb(or PyDev for Eclipse - same problem). Just for
> > completeness - here is one:
>
> >   PyRun_SimpleString("import sys");
> >   PyRun_SimpleString("import os");
> >   PyRun_SimpleString( "fullpath = os.path.abspath(\"E:/Test.py\")" );
> >   PyRun_SimpleString( "g = globals().copy()" );
> >   PyRun_SimpleString( "g['__file__'] = fullpath");
> >   PyRun_SimpleString( "execfile(fullpath, g) ");
> > <<<
>
> > If I use pdb (import pdb + pdb.runcall(something) ) everything works
> > fine, but I need the performance and convinience ofWinpdb.
>
> > What am I doing wrong?
>
> > Your help is highly appreciated!
>
> > Best regards,
> > Chris

Nir,

> Does this work?

Unfortunately, not.

I did some experiments to check the sys.path hypothesis:

- In my MSVC++ application I did PyRun_SimpleString("import cgi"); -
it complained about missing _socket.

- Did PyRun_SimpleString("print sys.path") to get the sys.path as seen
from within the application environment (that does not find _socket)

- Did the same in "test.py" and ran ...>Python test.py to get the
sys.path for the environment that _does_ find _socket

- Compared the two - the working environment had two more paths:

  C:\\WINDOWS\\system32\\python25.zip
  C:\\Python25\\lib\\plat-win

- Added the missing path to the embedded environment:

  PyRun_SimpleString("import sys");
  PyRun_SimpleString("import os");

  PyRun_SimpleString("sys.path.append(\"C:\\WINDOWS\\system32\
\python25.zip\")");
  PyRun_SimpleString("sys.path.append(\"C:\\Python25\\lib\\plat-win
\")");

  PyRun_SimpleString("print sys.path");

  PyRun_SimpleString("import cgi");

Not all paths that are in the working environment are present in the
embedded environment, but still there is a problem:

Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\Lib\cgi.py", line 40, in 
import urllib
  File "c:\Python25\lib\urllib.py", line 26, in 
import socket
  File "c:\Python25\lib\socket.py", line 45, in 
import _socket
ImportError: No module named _socket

Chris



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


Change in interactive interpreter?

2008-06-06 Thread The Pythonista
I remember the interactive interpreter used to define the name _ to 
return the value of the last expression that was evaluated.  However, I 
tried it just today and got a NameError.  Is this a change in the 
interpreter or is there a configuration option I need to set to enable it?

Thanks!

-- 
code.py: A blog about life, the universe, and Python

http://pythonista.wordpress.com
** Posted from http://www.teranews.com **
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cannot use Winpdb (or PyDev) to trace embedded Python script in MSVC++ application - ImportError: No module named _socket

2008-06-06 Thread Chris8Boyd
On Jun 6, 11:25 am, [EMAIL PROTECTED] wrote:
> On Jun 6, 1:13 am, Nir <[EMAIL PROTECTED]> wrote:
>
>
>
> > You seem to be having a problem with the import path of the embedded
> > interpreter. I suppose the embedded interpreter includes some modules
> > in a particular folder and _socket is not one of them. For the sake of
> > debugging try adding the c:\python25\lib path to the sys.path variable
> > of the interpreter before attempting to import rpdb2.
>
> > Does this work?
>
> > Nir
>
> > On Jun 5, 2:52 pm, [EMAIL PROTECTED] wrote:
>
> > > I am embedding Python in a MSVC++ (2005) application. The application
> > > creates some environment and then launches a Python script that will
> > > call some functions exported from the MSVC++ application.
>
> > > I want to be able to debug the Python script by using a debug server,
> > > likeWinpdb(winpdb.org).
>
> > > I use ActivePython 2.5.2.2, Microsoft Visual Studio 2005, andWinpdb
> > > 1.3.8.
>
> > > When I launch a script like "e:>python test.py" everything is O'K and
> > > I can useWinpdbto trace/debug.
>
> > > When I run the same script from the MSVC++ application, there is
> > > always a complain "ImportError: No module named _socket".
>
> > > Here is the basic test script I use:
>
> > > def Process( something ):
> > > print "\n\nStarted debugging\n=\n"
> > > #pydevd.settrace()
> > > import rpdb2; rpdb2.start_embedded_debugger("1")
> > > print "\n\nStopped debugging\n=\n"
>
> > > if __name__ == '__main__':
> > > Process( "test" )
> > > <<<
>
> > > In the MSVC++ application I tried many approaches, as suggested by
> > > many people, and all of them work to launch the script, but none of
> > > them works withWinpdb(or PyDev for Eclipse - same problem). Just for
> > > completeness - here is one:
>
> > >   PyRun_SimpleString("import sys");
> > >   PyRun_SimpleString("import os");
> > >   PyRun_SimpleString( "fullpath = os.path.abspath(\"E:/Test.py\")" );
> > >   PyRun_SimpleString( "g = globals().copy()" );
> > >   PyRun_SimpleString( "g['__file__'] = fullpath");
> > >   PyRun_SimpleString( "execfile(fullpath, g) ");
> > > <<<
>
> > > If I use pdb (import pdb + pdb.runcall(something) ) everything works
> > > fine, but I need the performance and convinience ofWinpdb.
>
> > > What am I doing wrong?
>
> > > Your help is highly appreciated!
>
> > > Best regards,
> > > Chris
>
> Nir,
>
> > Does this work?
>
> Unfortunately, not.
>
> I did some experiments to check the sys.path hypothesis:
>
> - In my MSVC++ application I did PyRun_SimpleString("import cgi"); -
> it complained about missing _socket.
>
> - Did PyRun_SimpleString("print sys.path") to get the sys.path as seen
> from within the application environment (that does not find _socket)
>
> - Did the same in "test.py" and ran ...>Python test.py to get the
> sys.path for the environment that _does_ find _socket
>
> - Compared the two - the working environment had two more paths:
>
>   C:\\WINDOWS\\system32\\python25.zip
>   C:\\Python25\\lib\\plat-win
>
> - Added the missing path to the embedded environment:
>
>   PyRun_SimpleString("import sys");
>   PyRun_SimpleString("import os");
>
>   PyRun_SimpleString("sys.path.append(\"C:\\WINDOWS\\system32\
> \python25.zip\")");
>   PyRun_SimpleString("sys.path.append(\"C:\\Python25\\lib\\plat-win
> \")");
>
>   PyRun_SimpleString("print sys.path");
>
>   PyRun_SimpleString("import cgi");
>
> Not all paths that are in the working environment are present in the
> embedded environment, but still there is a problem:
>
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "C:\Python25\Lib\cgi.py", line 40, in 
> import urllib
>   File "c:\Python25\lib\urllib.py", line 26, in 
> import socket
>   File "c:\Python25\lib\socket.py", line 45, in 
> import _socket
> ImportError: No module named _socket
>
> Chris

There is a typo:

"Not all paths that are in the working environment are present in the
embedded environment, but still there is a problem:"

should read

"Now all paths"

Sorry!

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


Re: Change in interactive interpreter?

2008-06-06 Thread Gary Herron

The Pythonista wrote:
I remember the interactive interpreter used to define the name _ to 
return the value of the last expression that was evaluated.  However, I 
tried it just today and got a NameError.  Is this a change in the 
interpreter or is there a configuration option I need to set to enable it?


Thanks!

  


Try again.  I think you'll find it's still there -- although you have to 
execute a something that returns a value before it's set for the first time.


Gary Herron


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


Re: Do this as a list comprehension?

2008-06-06 Thread The Pythonista
On Thu, 05 Jun 2008 23:42:07 -0400, John Salerno wrote:

> Is it possible to write a list comprehension for this so as to produce a
> list of two-item tuples?
> 
> base_scores = range(8, 19)
> score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] print zip(base_scores,
> score_costs)
> 

score_costs = [(base_scores[i], score_costs[i]) for i in range (len 
(base_scores))]

But, I'd rather just use zip. :-)

-- 
code.py: A blog about life, the universe, and Python

http://pythonista.wordpress.com
** Posted from http://www.teranews.com **
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to kill a thread?

2008-06-06 Thread The Pythonista
It's always been my understanding that you can't forcibly kill a thread 
in Python (at least not in a portable way).  The best you can do is 
politely ask it to die, IIRC.

-- 
code.py: A blog about life, the universe, and Python

http://pythonista.wordpress.com
** Posted from http://www.teranews.com **
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why does python not have a mechanism for data hiding?

2008-06-06 Thread Russ P.
On Jun 6, 8:25 am, Bruno Desthuilliers  wrote:

> >>> I also realize, by the way, that Python allows a client of a class to
> >>> define a new class member from completely outside the class
> >>> definition. Obviously, that cannot be declared private.
> >> Why so ?
>
> > Why should the client of a class not be able to declare a *private*
> > member of the class? You're kidding, right?
>
> I'm dead serious. I often add implementation attributes to either a
> class or an instance. These *are* implementation parts, not API.

If a client accesses a data member of a class, then by definition that
member is not really private, so letting the client create a new data
member and declare it as private seems a bit silly to me. Actually,
just letting the client create the new data member, private or not,
seems like a bit of a stretch to me, but I'll leave that be.

> > For the record, I have made it abundantly clear that I don't think
> > Python should not have as rigorous an encapsulation regime as C++ or
> > Java. The worst that could happen with my proposition is that you
> > would need to use a "mangled" name to access private data or methods.
>
> That's already the case - when you use __name_mangling. And if there's
> no effective access restriction, then what the point of having this
> 'priv' keyword ?
>
> > But you will be using the name many times, you can reassign your own
> > name, of course, so the mangled name need not appear more than once
> > where it is needed.
>
> Once again, I just don't see the point. Either you want effective access
> restriction in Python, or you don't. And if you don't, what would this
> 'priv' keyword be useful to ?

In the end, I suppose it boils down to aesthetics and personal
preference.

The leading-underscore convention bothers me for two reasons: (1) like
the OP, I don't like the way it makes my code look, and (2) it is a
signal to a person reading the code, but it has no actual effect in
the interpreter.

I think the concept of private data and methods is important enough to
be implemented with more than just a tacky naming convention. That is
why I suggested the "priv" keyword. At the same time, I realize that
people will occasionally be frustrated if they are rigorously denied
access to all private data, which is why I suggested an "indirect"
method of access through mangled names.

You can argue that such indirect access defeats the whole idea of
private data, but at least it alerts the client to the fact that he
(or she or it) is accessing private data -- and it does so without
using Hungarian notation.

I would let the "priv" keyword also be used for data or functions at
file scope. It just seems logical to me. Again, some name mangling
convention could be concocted for those who think they really need
access.

Actually, the whole objection to denied access baffles me a bit. Does
anyone object to not having access from outside a function to local
variables within the function? I doubt it. The other thing is that the
vast majority of Python software, I would guess, is provided with
source code. How many Python applications or libraries are provided
without source code? If you have the source code, you can obviously
just delete the "priv" keyword anywhere or everywhere it appears. And
if you have a major client who insists on access to all the internals,
just delete all occurrences of "priv" before you ship the code (or
don't use it to start with).

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


Re: Why does python not have a mechanism for data hiding?

2008-06-06 Thread Russ P.
On Jun 6, 8:28 am, Bruno Desthuilliers  wrote:
> Russ P. a écrit :
>
>
>
> > On Jun 5, 2:27 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> >> On Thu, 5 Jun 2008 11:36:28 -0700 (PDT), "Russ P."
> >> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
> >>> would need to use a "mangled" name to access private data or methods.
> >>> But you will be using the name many times, you can reassign your own
> >>> name, of course, so the mangled name need not appear more than once
> >>> where it is needed.
> >> Which will break the first time the "innards" rebind a value to the
> >> mangled name, as the "simplified" external name will still be bound to
> >> the previous value.
>
> > I'm not sure you understood what I meant. In current Python, if I need
> > access to data element __XX in class YourClass, I can use
> > ZZ._YourClass__XX, but if I don't want to clutter my code with that
> > mangled name, I can just write
>
> > XX = ZZ._YourClass__XX
>
> > and refer to it from that point on as XX.
>
> > Obviously if the meaning of
> > __XX changes within class ZZ, this will break, but that's why you are
> > supposed to avoid using private data in the first place.
>
> AFAICT, What Dennis meant is that the binding of ZZ._YourClass__XX
> changes between the moment you bind it to local XX and the moment you
> use it, then you're out.

Perhaps I should have stipulated that this should be done only in a
local scope and in an application that is not multi-threaded. Then I
don't see how you can have a problem.
--
http://mail.python.org/mailman/listinfo/python-list


Re: File-writing not working in Windows?

2008-06-06 Thread jay graves
On Jun 6, 1:22 pm, [EMAIL PROTECTED] wrote:
> I am thinking that the "g.open(tempFileName, 'a')" command is the
> issue.  Is there anything different about opening a file in Windows?
> Does Windows understand "append", or would I have to do control checks
> for seeing if the file is created and then appending?

Does your file have embedded nulls?
Try opening it in binary mode.

g.open(tempFileName,'ab')

Note that this will turn off Universal newline support.

Barring that, can you distill the problem down by writing a script
that exhibits the behavior without the rest of your program?

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


Re: Assigning to __class__ : bad form?

2008-06-06 Thread [EMAIL PROTECTED]
On 6 juin, 19:51, The Pythonista <[EMAIL PROTECTED]> wrote:
> I've been wondering for a while about whether assigning to __class__ is
> bad form or not.  Specifically, I mean doing so when some other method of
> implementing the functionality you're after is available (i.e. using an
> adapter, or something like the strategy pattern).
>
> To give an example and a non-example of what I'm talking about, consider
> the following recipes from the online Python Cookbook:
>
> Ring Buffer:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68429
>
> In this case, I think the assignment to __class__ just obfuscates things,
> and the example would be better coded as a single class.
>
> On the other hand,
>
> Fast copy of an object having a slow __init__ : http://
> aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66507
>
> This seems like a reasonable use case for assigning to __class__ (except
> that it's already implemented in the 'new' module, but, read the Martelli-
> bot's comments near the end of the recipe).  I consider this a reasonable
> use case for assigning to __class__, because, short of the 'new' module,
> I don't see any other way to accomplish it.
>
> So, what is the opinion of the broader Python community?

My first opinion is that your formulation, ie "assigning *to*
__class__" is perhaps a bit misleading. What you're talking about is
rebinding the __class__ attribute, while, from your subject line, I
thought you were talking about reassigning to (rebinding) a class
attribute from the instance, ie : self.__class__.attrib = value.

Now to the point:

>  Is code that
> assigns to __class__ just clever trickiness to be avoided, or is it
> sometimes a good thing?

Both, definitively !-)

Like most of Python's "advanced" features, it's nice to have it
because it can easily solve problems that would otherwise be at best a
PITA, but it's not something you use on a daily basis - nor without
thinking twice. And obviously, there's no clear rule here, except good
taste and common sense. Anyway, the mere fact that you're asking
yourself if it's a good idea in such or such case is a probably a good
indication that you'll find out by yourself the day you'll be tempted
to use this trick whether it's a good or bad idea in this particular
context.
--
http://mail.python.org/mailman/listinfo/python-list


Re: noob question : library versus normal python files

2008-06-06 Thread [EMAIL PROTECTED]
On 6 juin, 19:36, रवींदर ठाकुर (ravinder thakur)
<[EMAIL PROTECTED]> wrote:
> hello friends,
>
> i have a python library(rdflib) that i am using in some project using
> Google App Engine. I have developed everything using this on my local
> machine and things work fine. But in my final deployment, i have to
> use it in source code form rather than in library form.

What do you mean "library form" ?
--
http://mail.python.org/mailman/listinfo/python-list

Trying to install mysql lib for python

2008-06-06 Thread [EMAIL PROTECTED]
Hi
How do I install mysql db libray for python?
I went to source forg and downloaded the following zip folder

MySQL_python-1.2.2-py2.4-win32
I open the folder and looked inside did not see any directions.

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


Re: File-writing not working in Windows?

2008-06-06 Thread tdahsu
On Jun 6, 2:58 pm, jay graves <[EMAIL PROTECTED]> wrote:
> On Jun 6, 1:22 pm, [EMAIL PROTECTED] wrote:
>
> > I am thinking that the "g.open(tempFileName, 'a')" command is the
> > issue.  Is there anything different about opening a file in Windows?
> > Does Windows understand "append", or would I have to do control checks
> > for seeing if the file is created and then appending?
>
> Does your file have embedded nulls?
> Try opening it in binary mode.
>
> g.open(tempFileName,'ab')
>
> Note that this will turn off Universal newline support.
>
> Barring that, can you distill the problem down by writing a script
> that exhibits the behavior without the rest of your program?
>
> ...
> Jay

Jay,

This did not make a difference in my script.  However, I did what you
suggested, and tried the simple script it Windows, and it works as it
should.

(It's really annoying because it works on the Mac and Linux!  (I just
tested my script on the Mac as well.)  It only doesn't work on
Windows, though clearly the file processing I am doing SHOULD work.)

Now I have to find out what it is about my code that's causing the
problem...  :-(
--
http://mail.python.org/mailman/listinfo/python-list


Re: Do this as a list comprehension?

2008-06-06 Thread John Salerno
"Mensanator" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
On Jun 6, 1:44 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> "Mensanator" <[EMAIL PROTECTED]> wrote in message

And since the OP foolishly
hardcoded his range bounds

Hmm, I just love the arrogance of some people. I actually posted a response 
to my own thread that asked about this situation of how best to make the 
range, but it doesn't seem to have posted. 


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


Re: File-writing not working in Windows?

2008-06-06 Thread jay graves
On Jun 6, 3:19 pm, [EMAIL PROTECTED] wrote:
> This did not make a difference in my script.  However, I did what you
> suggested, and tried the simple script it Windows, and it works as it
> should.
> (It's really annoying because it works on the Mac and Linux!  (I just
> tested my script on the Mac as well.)  It only doesn't work on
> Windows, though clearly the file processing I am doing SHOULD work.)

Is there a global exception handler somewhere in your code that could
be eating an error that only happens on windows?  (something weird
like file permissions.)  I'm really at a loss.

Sorry.

...
Jay




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


Re: ClassName.attribute vs self.__class__.attribute

2008-06-06 Thread Casey McGinty
On Thu, Jun 5, 2008 at 11:39 AM, Terry Reedy <[EMAIL PROTECTED]> wrote:

>
> If you want to access the attribute of a particular class, to read or
> write, use that class.
>   SomeClass.attr
> Note that no instance is required or relevant.
>
> If you want to read the attrubute of the class of an instance (or the first
> superclass with the attribute, whatever that class might be, use self.attr
> or self.__class__.attr.  (Use the latter if the instance has (or might
> have) an attribute of the same name).
>
> For setting an attribute, self.attr = x sets it on the instance while
> self.__class__.attr = x sets it on its class.
>  
>

So the key here is that obj.__class__.attr  will only access  the immediate
child class name space, but SuperClass.attr will guarantee your are access
the first super class namespace? If that is true, then the bug makes sense.
--
http://mail.python.org/mailman/listinfo/python-list

[ANN] Dramatis 0.1.1 released

2008-06-06 Thread Steven Parkes
The first alpha release of dramatis hit the streets today.

dramatis is a library available in Python and Ruby used to write concurrent
programs based on the actor model of concurrency.

The dramatis web site is http://dramatis.mischance.net

The release is available as a python distutils package at
http://pypi.python.org/pypi/dramatis. It supports both Ruby and Python, and
comes with API docs, several examples, and a tutorial.

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


Re: Guide to organizing modules?

2008-06-06 Thread Casey McGinty
>
> Yes, in the above post I meant to say package where I said module.
> Right now all my functions are in the __init__.py script, and I would
> consider separating them out into sub-packages, if it had any rhyme or
> reason, but right now that escapes me. That's mostly what I'm trying
> to ask for.
>
> Thanks,
> --Buck
>  
>

Have you thought about  creating a number of new module files in your
package, and importing them into __init__.py? If you do that you could hide
the fact that the functions are in distinct files from outside of the
package.

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

Re: Q about object identity

2008-06-06 Thread Ethan Furman

[EMAIL PROTECTED] wrote:

Hello,

I am testing object identity.

If I do it from the interpreter, I get strange results.



*print [] is []*


*False*



print id([]), id([])


3083942700 3083942700



Why is that? Isn't this an error?


If I test it in a script, all is OK.

#!/usr/bin/python

a = []
b = []

print a == b
*print a is b*

print id(a), id(b)

print id(None), id(None)
print id(True), id(True)


On my computer, I got these results:

True
*False*
3083769036 3083793516
135553336 135553336
135526444 135526444

All as expected.


jan bodnar


Assuming I'm not missing something obvious here, the results from the 
script are the same as those from the interpreter -- the _is_ returns 
False in both cases.

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


Macro like functionality for shorthand variable names

2008-06-06 Thread Tilman Kispersky
I have python code in a class method translated from C++ that looks
sort of like this:

>>>  self.dydt[1] = self.a * (self.b * self.y[0] - self.y[1])


To make this more readable in C++ I had made macros to achieve this:
#define du (dydt[1])
#define u (y[1])
#define V (y[0])

du = a * (b * V - u);


I realize the value of not having macros in Python.  They've tripped
me up more than once in C++.  My question is:
Is there any way to write a shorterhand more readable version of the
python code above?  I'm doing several calculations one after the other
and some of the lines are quite long.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Q about object identity

2008-06-06 Thread Tommy Grav


On Jun 6, 2008, at 4:27 PM, Ethan Furman wrote:


[EMAIL PROTECTED] wrote:

Hello,
I am testing object identity.
If I do it from the interpreter, I get strange results.

*print [] is []*

*False*

print id([]), id([])

3083942700 3083942700
Why is that? Isn't this an error?


in the first statement the two []'s are in memory at the same
time and have different id() signatures. For the second statement
the first id([]) is evaluated and release from memory and then
the second id([]) is evaluated and release from memory. Since
only one of them exist at a time they can have the same id()
signature.

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


Learning which modules were loaded

2008-06-06 Thread James Stroud
I am rolling up a distribution of a program I wrote. It uses matplotlib 
with tkagg so the bundle is HUGE (47 MB, 14 MB after bz compression). Is 
there any way to run the program, put it through all of its paces, and 
then inspect which modules were loaded. I would like to gather these in 
a list and delete any others that py2app and py2exe attempt to include. 
Currently, these (or py2app, at least) use dependency graphing and 
icnlude everything belonging to pylab, matplotlib, and numpy by default. 
I don't want everything, I only want what my program needs to run. For 
example, some modules are imported by functions (in Pmw, for example) 
that never get called. I don't want to include these.


Thanks in advance for any help.

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


Re: Learning which modules were loaded

2008-06-06 Thread Gary Herron

James Stroud wrote:
I am rolling up a distribution of a program I wrote. It uses 
matplotlib with tkagg so the bundle is HUGE (47 MB, 14 MB after bz 
compression). Is there any way to run the program, put it through all 
of its paces, and then inspect which modules were loaded. I would like 
to gather these in a list and delete any others that py2app and py2exe 
attempt to include. Currently, these (or py2app, at least) use 
dependency graphing and icnlude everything belonging to pylab, 
matplotlib, and numpy by default. I don't want everything, I only want 
what my program needs to run. For example, some modules are imported 
by functions (in Pmw, for example) that never get called. I don't want 
to include these.


Thanks in advance for any help.

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


Import sys, then look at sys.modules.  It's a dictionary that contains 
all the imported modules, but I suspect you'll find that it's much 
easier to let py2app and py2exe determine what's imported than it is to 
go through sys.modules yourself.


Gary Herron

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


How to send a POST request?

2008-06-06 Thread kj



Hi.  Sorry for this very clueless question, but how does one write
in Python an HTTP client that can send a POST request?  The modules
I've found (e.g. urllib, urllib2), as far as I can tell, seem to
be limited to GET requests.  (I could be wrong though; please
correct me if this is so.)

TIA!

kynn

-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
--
http://mail.python.org/mailman/listinfo/python-list


Newbie question, list comprehension

2008-06-06 Thread Johannes Bauer

Hello group,

I'm currently doing something like this:

import time
localtime = time.localtime(1234567890)
fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % (localtime[0], localtime[1], 
localtime[2], localtime[3], localtime[4], localtime[5])

print fmttime

For the third line there is, I suppose, some awesome python magic I 
could use with list comprehensions. I tried:


fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % ([localtime[i] for i in 
range(0, 5)])


But that didn't work:

Traceback (most recent call last):
  File "./test.py", line 8, in ?
fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % ([localtime[i] for i in 
range(0, 5)])

TypeError: int argument required

As it appearently passed the while list [2009, 02, 14, 0, 31, 30] as the 
first parameter which is supposed to be substituted by "%04d". Is there 
some other way of doing it?


Thanks a lot,
Regards,
Johannes

--
"Wer etwas kritisiert muss es noch lange nicht selber besser können. Es
reicht zu wissen, daß andere es besser können und andere es auch
besser machen um einen Vergleich zu bringen." - Wolfgang Gerber
  in de.sci.electronics <[EMAIL PROTECTED]>
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to send a POST request?

2008-06-06 Thread kj
In <[EMAIL PROTECTED]> kj <[EMAIL PROTECTED]> writes:

>Hi.  Sorry for this very clueless question, but how does one write
>in Python an HTTP client that can send a POST request?  The modules
>I've found (e.g. urllib, urllib2), as far as I can tell, seem to
>be limited to GET requests.  (I could be wrong though; please
>correct me if this is so.)

Sorry, my mistake.  I now see that urllib2 handles POSTs too.

kynn

-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question, list comprehension

2008-06-06 Thread Hans Nowak

Johannes Bauer wrote:

Hello group,

I'm currently doing something like this:

import time
localtime = time.localtime(1234567890)
fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % (localtime[0], localtime[1], 
localtime[2], localtime[3], localtime[4], localtime[5])

print fmttime

For the third line there is, I suppose, some awesome python magic I 
could use with list comprehensions. I tried:


fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % ([localtime[i] for i in 
range(0, 5)])


The % operator here wants a tuple with six arguments that are integers, not a 
list.  Try:


fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % tuple(localtime[i] for i in 
range(6))


As it appearently passed the while list [2009, 02, 14, 0, 31, 30] as the 
first parameter which is supposed to be substituted by "%04d". Is there 
some other way of doing it?


In this case, you can just use a slice, as localtime is a tuple:

fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % localtime[:6]

Hope this helps! ^_^

--
Hans Nowak (zephyrfalcon at gmail dot com)
http://4.flowsnake.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Change in interactive interpreter?

2008-06-06 Thread The Pythonista
On Fri, 06 Jun 2008 11:36:13 -0700, Gary Herron wrote:
   
> Try again.  I think you'll find it's still there -- although you have to
> execute a something that returns a value before it's set for the first
> time.

That was, indeed the problem.  Boy do I feel silly now. :-)

Thanks

-- 
code.py: A blog about life, the universe, and Python

http://pythonista.wordpress.com
** Posted from http://www.teranews.com **
--
http://mail.python.org/mailman/listinfo/python-list


how to build a street with more than 1 house ?

2008-06-06 Thread Stef Mientki

hello,

In the code below, I can build a large street like this:
 large_street = house * 25
but not a small street. like this:
 small_street = 5 * house

Why is this different ?
And more interesting, how do I get the right results ?

thanks,
Stef Mientki

class type_house ( object ) :
 def __init__( self, front_doors = 1 ) :
   self.front_doors = front_doors
 def __mul__ ( self, b ) :
   return type_house ( self.front_doors * b )

house = type_house ()
large_street = house * 25
print large_street.front_doors
small_street = 5 * house
print small_street.front_doors

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


Re: Newbie question, list comprehension

2008-06-06 Thread Johannes Bauer

Hans Nowak schrieb:


In this case, you can just use a slice, as localtime is a tuple:

fmttime = "%04d-%02d-%02d %02d:%02d:%02d" % localtime[:6]

Hope this helps! ^_^


Ahh, how cool! That's *exactly* what I meant with "awesome Python magic" :-)

Amazing language, I have to admit.

Regards,
Johannes

--
"Wer etwas kritisiert muss es noch lange nicht selber besser können. Es
reicht zu wissen, daß andere es besser können und andere es auch
besser machen um einen Vergleich zu bringen." - Wolfgang Gerber
  in de.sci.electronics <[EMAIL PROTECTED]>
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to build a street with more than 1 house ?

2008-06-06 Thread Tommy Grav


On Jun 6, 2008, at 6:45 PM, Stef Mientki wrote:


hello,

In the code below, I can build a large street like this:
large_street = house * 25
but not a small street. like this:
small_street = 5 * house


This calls the int.__mul__() code i believe.


Why is this different ?
And more interesting, how do I get the right results ?


If memory serves me right look into __rmul__().

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


Re: readline() & seek() ???

2008-06-06 Thread Kam-Hung Soh

Chris wrote:

On Jun 6, 5:13 am, Kam-Hung Soh <[EMAIL PROTECTED]> wrote:

Tim Roberts wrote:

DataSmash <[EMAIL PROTECTED]> wrote:

I have a text file that contains thousands of lines and each line is
256 characters long.
This is my task:
For each line in the file, move to the 25th character, if the
character is a "T",
move to the 35th character of the line and read 5 characters from
there.
Capture these 5 characters and write them to a new text file, each 5
characters separated by a comma.
I appreciate your help!

Did you even TRY this?  Your task reads like pseudocode that translates
virtually line-for-line to Python code.
  fout = open('outputfile.txt','w')
  for line in open('inputfile.txt'):
  if line[24] == 'T':
  fout.write( line[34:39] + ',' )

Should the last line be ...

fout.write(','.join(line[34:39])

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman


each 5 characters need to be delimited by a comma, your statement
would have a comma between each of the 5 characters.


You're right; I see where I got confused.

--
Kam-Hung Soh http://kamhungsoh.com/blog";>Software Salariman

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


Re: File-writing not working in Windows?

2008-06-06 Thread John Machin
On Jun 7, 1:18 am, [EMAIL PROTECTED] wrote:
> All,
>

[code snipped]

>
> This code works PERFECTLY in Linux.  Where I have a match in the file
> I'm processing, it gets cut out from the start of the match until the
> end of the match, and written to the temporary file in tempdir.
>
> It does not work in Windows.  It does not create or write to the
> temporary file AT ALL.  It creates the tempdir directory with no
> problem.
>
> Here's the kicker: it works perfectly in Windows if Windows is running
> in VMware on a Linux host!  (I assume that that's because VMware is
> passing some call to the host.)
>
> Can anyone tell me what it is that I'm missing which would prevent the
> file from being created on Windows natively?
>
> I'm sorry I can't provide any more of the code, and I know that that
> will hamper your efforts in helping me, so I apologise up front.
>
> Assumptions:
> You can assume self.checkbox25.GetValue() is always false for now, and
> self.Info[x][0] contains a two character string like "00" or "09" or
> "14".  There is always a match in the fileTarget, so self.Info[x][2]
> will always be true at some point, as will self.Info[x][4].  I am
> cutting an HTML file at predetermined comment sections, and I have
> control over the HTML files that are being cut.  (So I can force the
> file to match what I need it to match if necessary.)

Assume nothing. Don't believe anyone who says "always". Insert some
print statements and repr() calls to show what's actually there.

> I hope however that it's something obvious that a Python guru here
> will be able to spot and that this n00b is missing!

*IF* the problem is in the code, it would be easier to spot if you had
removed large chunks of indentation before posting.

Less is more: change "if (foo == 2):" to "if foo == 2:", "foo == True"
to "foo", and "foo == False" to "not foo".

Browse http://www.python.org/dev/peps/pep-0008/

HTH,
John
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python is slow

2008-06-06 Thread Jan Claeys
Op Fri, 23 May 2008 14:00:33 -0700, schreef [EMAIL PROTECTED]:

> Now this I can tell is false. The problem is not that it's difficult to
> "make a native compiler for" dynamic languages, the problem is that it's
> difficult to write native compiler for dynamic languages that generates
> code that beats the VM/byte-code interpreter/whatever you name it to be
> wotrh the effort.

Well, it would be much easier if there would be hardware that was 
designed for object oriented & dynamic programming...  ;-)

(Most current hardware is designed for use with C & similar languages, or 
sometimes for massively parrallel computing (e.g. GPUs), but the last 
tries to design hardware to fit something like Python date back to the 
1980s AFAIK...)


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


Re: How to send a POST request?

2008-06-06 Thread Jeff McNeil
The original urllib module will do it too, if you pass a data keyword
argument to urllib.urlopen:

u = urllib.urlopen('http://www.domain.com/cgi-bin/cgi.py',
data=urllib.urlencode({'name': 'pythonguy'}))


On Fri, Jun 6, 2008 at 6:04 PM, kj <[EMAIL PROTECTED]> wrote:
> In <[EMAIL PROTECTED]> kj <[EMAIL PROTECTED]> writes:
>
>>Hi.  Sorry for this very clueless question, but how does one write
>>in Python an HTTP client that can send a POST request?  The modules
>>I've found (e.g. urllib, urllib2), as far as I can tell, seem to
>>be limited to GET requests.  (I could be wrong though; please
>>correct me if this is so.)
>
> Sorry, my mistake.  I now see that urllib2 handles POSTs too.
>
> kynn
>
> --
> NOTE: In my address everything before the first period is backwards;
> and the last period, and everything after it, should be discarded.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Do this as a list comprehension?

2008-06-06 Thread Mensanator
On Jun 6, 3:19 pm, "John Salerno" <[EMAIL PROTECTED]> wrote:
> "Mensanator" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
> On Jun 6, 1:44 am, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
>
> > "Mensanator" <[EMAIL PROTECTED]> wrote in message
>
> And since the OP foolishly
> hardcoded his range bounds
>
> Hmm, I just love the arrogance of some people. I actually posted a response
> to my own thread that asked about this situation of how best to make the
> range, but it doesn't seem to have posted.

It wasn't meant to be arrogant. Just that you must be careful
with zip() because it will not throw an exception if the two
iterables are of different length (this behaviour is by design)
but simply return tuples for the shorter of the iterables.

Hardcoding the range bounds instead of setting them dynamically
is a classic cause of this type of error. Obviously, you want the
range to start with 8, but what should be the upper bound?
The start plus the length of the other iterable keeping in mind
that if length is 11, last index is 8+10 since counting starts at 0.

So you want

range(8,8+len(score_costs))

Using enumerate() means you don't have to figure this out and
you'll never get an error or bad results that don't make an
error.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Do this as a list comprehension?

2008-06-06 Thread Mensanator
On Jun 6, 1:40 pm, The Pythonista <[EMAIL PROTECTED]> wrote:
> On Thu, 05 Jun 2008 23:42:07 -0400, John Salerno wrote:
> > Is it possible to write a list comprehension for this so as to produce a
> > list of two-item tuples?
>
> > base_scores = range(8, 19)
> > score_costs = [0, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3] print zip(base_scores,
> > score_costs)
>
> score_costs = [(base_scores[i], score_costs[i]) for i in range (len
> (base_scores))]

What happens if your iterables aren't the same length?

>
> But, I'd rather just use zip. :-)

And with zip() you won't get an error, but it won't be correct,
either.

>
> --
> code.py: A blog about life, the universe, and Python
>
> http://pythonista.wordpress.com
> ** Posted fromhttp://www.teranews.com**

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


need really help

2008-06-06 Thread Golu
respected please help me i am really need of money please pay me
through donation from my site. http://www.computersolution.co.cc i
will be very thankful to you . please donate atleast 5$ or 2$ through
my site
http://www.computersolution.co.cc hope i will be able to clear my
debts because of you all
--
http://mail.python.org/mailman/listinfo/python-list


Dynamically naming objects.

2008-06-06 Thread Kalibr
I've been developing a small script to fiddle with classes, and came
accross the following problem. Assuming I get some user input asking
for a number, how would I spawn 'n' objects from a class?

i.e. I have a class class 'user' and I don't know how many of them I
want to spawn.

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


Re: Dynamically naming objects.

2008-06-06 Thread Hans Nowak

Kalibr wrote:

I've been developing a small script to fiddle with classes, and came
accross the following problem. Assuming I get some user input asking
for a number, how would I spawn 'n' objects from a class?

i.e. I have a class class 'user' and I don't know how many of them I
want to spawn.

Any ideas?


Sure. This will give you a list of n instances of user:

  [user() for i in range(n)]

Of course, you could also use a good old for loop:

  for i in range(n):
  u = user()
  ...do something with u...

Hope this helps!

--
Hans Nowak (zephyrfalcon at gmail dot com)
http://4.flowsnake.org/
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >